import * as mc from '@minecraft/server';
import * as mcui from '@minecraft/server-ui';
import * as racoAPI from '../raco-API';
import { colorSelected } from './wirelessFunctions';
const activeTimeouts = new Map();

export function pressurePlateTick(block) {
    const blockKey = `${block.dimension.id},${block.location.x},${block.location.y},${block.location.z}`;
    const entitiesNear = block.dimension.getEntities({ location: block.center(), maxDistance: 0.75 });
    const isEntityNearby = entitiesNear.length > 0;

    if (isEntityNearby && !block.permutation.getState('vtng_rt:on')) {
        racoAPI.setPermutation(block, 'vtng_rt:on', true);
        block.dimension.spawnParticle('vtng_rt:redstone_out', block.center());
        block.dimension.playSound('random.click', block.center(), { pitch: 0.6, volume: 1 });
        mc.world.setDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)}`, `vtng_rt:${block.permutation.getState('vtng_rt:color')}`)
    }

    if (!activeTimeouts.has(blockKey)) {
        activeTimeouts.set(blockKey, true);

        mc.system.runTimeout(() => {
            const stillEntitiesNear = block.dimension.getEntities({ location: block.center(), maxDistance: 0.75 });
            if (!stillEntitiesNear.length && block.permutation.getState('vtng_rt:on')) {
                racoAPI.setPermutation(block, 'vtng_rt:on', false);
                block.dimension.playSound('random.click', block.center(), { pitch: 0.6, volume: 1 });
                mc.world.setDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)}`, undefined)
            }
            activeTimeouts.delete(blockKey);
        }, 20);
    }
}



export function pressurePlateInteract(player, block) {
    const item = player.getComponent('equippable')?.getEquipment("Mainhand")
    if (item?.typeId == 'vtng_rt:pliers') {
        const selectedColor = colorSelected(player, block, setModule)
    }
}
function setModule(block, color) {
    racoAPI.setPermutation(block, 'vtng_rt:color', color)
} 