import * as mc from '@minecraft/server';
import * as mcui from '@minecraft/server-ui';
import * as racoAPI from '../raco-API';
import { colorSelected } from './wirelessFunctions';

export function receiverTick(block){
    try {
        let on = mc.world.getDynamicPropertyIds().some(thisProperty =>
            mc.world.getDynamicProperty(thisProperty)?.replace('vtng_rt:', '') === block.permutation.getState('vtng_rt:color')
        )
        if (on){
            const faces = [
                block.north(),
                block.south(),
                block.west(),
                block.east()
            ]
            for (const sendBlock of faces){
                if (sendBlock?.typeId == 'minecraft:unpowered_repeater'){
                    const sendDirection = sendBlock.permutation.getState('minecraft:cardinal_direction')
                    const sendDelay = sendBlock.permutation.getState('repeater_delay')
                    if (JSON.stringify(sendBlock[sendDirection]().location) == JSON.stringify(block.location)){
                        block.dimension.runCommand(`setblock ${sendBlock.x} ${sendBlock.y} ${sendBlock.z} powered_repeater ["minecraft:cardinal_direction"="${sendDirection}", "repeater_delay"=${sendDelay}]`)
                    }
                }
            }
        }
        if (block.permutation.getState("vtng_rt:on") == false && on){
            const loc = {
                north:{x:block.center().x, y:block.center().y+0.25, z:block.center().z-0.19},
                south:{x:block.center().x, y:block.center().y+0.25, z:block.center().z+0.19},
                west:{x:block.center().x-0.19, y:block.center().y+0.25, z:block.center().z},
                east:{x:block.center().x+0.19, y:block.center().y+0.25, z:block.center().z}
            }
            block.dimension.spawnParticle('vtng_rt:redstone_inp', loc[block.permutation.getState('minecraft:cardinal_direction')])
        }
        racoAPI.setPermutation(block, 'vtng_rt:on', on)
    } catch (error){}
}

export function receiverInteract(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)
} 