import * as mc from "@minecraft/server"
import * as mcui from "@minecraft/server-ui"
import * as racoAPI from "../raco-API"
import { interactWithBlock } from "../systems/interactBlock"
import {hasRedstonePower} from "../hasRedstonePower"
import {getRedstonePower} from "../getRedstonePower"

export function breakerTick(block){
    const on = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'], true) ?? false;
    if (block.permutation.getState('vtng_rt:on') == false && on){
        const unbBlocks = [
            'minecraft:bedrock',
            'minecraft:command_block',
            'minecraft:obsidian'
        ];
        const frontBlock = block[racoAPI.blockFaceToDirection(block.permutation.getState('minecraft:facing_direction'))]()
        if (!unbBlocks.includes(frontBlock?.typeId)){
            block.dimension.runCommand(`setblock ${racoAPI.locToCommand(frontBlock)} air destroy`)
        }
    }
    if (block.permutation.getState('vtng_rt:on') != on) racoAPI.setPermutation(block, 'vtng_rt:on', on)
}

export function userInteract(player, block){
    const entity = block.dimension.getEntities({types:'vtng_rt:user_entity', location:block.center(), maxDistance:0.5, closest:1})[0] ? block.dimension.getEntities({types:'vtng_rt:user_entity', location:block.center(), maxDistance:0.5, closest:1})[0] : block.dimension.spawnEntity('vtng_rt:user_entity', block.center())
    entity.setProperty('vtng_rt:cardinal_rotation', racoAPI.invertUpDown(racoAPI.invertFace(block.permutation.getState('minecraft:facing_direction'))))
    const item = player.getComponent("equippable")?.getEquipment("Mainhand")
    if (entity){
        const container = entity?.getComponent("inventory")?.container
        if (player.isSneaking && !item && container?.getItem(0)){
            entity.dimension.spawnItem(container?.getItem(0), block.center())
            container.setItem(0, )
            entity.runCommand(`replaceitem entity @s slot.weapon.offhand 0 air`)
        }
        if (item){
            if (container?.getItem(0)?.typeId){
                entity.dimension.spawnItem(container?.getItem(0), block.center())
            }
            if (racoAPI.placerItemIsBlock(block, item) || ['minecraft:bone_meal', 'minecraft:flint_and_steel', '_shovel', '_hoe', '_axe'].some(type => item.typeId.includes(type))) {
                mc.system.run(()=>{
                    entity.runCommand(`replaceitem entity @s slot.weapon.offhand 0 ${item?.typeId}`)
                    container.setItem(0, item)
                    player.getComponent("equippable")?.setEquipment("Mainhand", )
                })
            };
            if (racoAPI.itemIsBlock(block, item)){
                entity.setProperty('vtng_rt:type', 1)
            } else entity.setProperty('vtng_rt:type', 0)
        }
    }
}
export function userTick(block){
    const on = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'], true) ?? false;
    const entity = block.dimension.getEntities({types:'vtng_rt:user_entity', location:block.center(), maxDistance:0.5, closest:1})[0];

    if (!entity) mc.system.runTimeout(() => {
        const entity = block.dimension.getEntities({types:'vtng_rt:user_entity', location:block.center(), maxDistance:0.5, closest:1})[0];
        if (!entity) block.dimension.runCommand(`setblock ${block.x} ${block.y} ${block.z} air destroy`)
    }, 10);
    
    const container = entity?.getComponent("inventory")?.container
    const faces = [
        'north',
        'south',
        'west',
        'east',
        'above'
    ]
    let shouldBreak = false;
    const direction = block.permutation.getState('minecraft:facing_direction')
    for (const thisFace of faces) {
        if (thisFace != racoAPI.invertFace(direction)) {
            const thisBlock = block[thisFace]();
            if (thisBlock?.typeId == 'minecraft:hopper') {
                const hopperContainer = thisBlock.getComponent('inventory')?.container;
                for (let i = 0; i < hopperContainer.size; i++) {
                    const thisItem = hopperContainer.getItem(i);
                    if (thisItem) {
                        if (!container?.getItem(0)){
                            const newItem = thisItem
                            if (thisItem?.amount > 1){
                                thisItem.amount = thisItem.amount-1
                                hopperContainer.setItem(i, thisItem)
                            } else if (thisItem?.amount == 1){
                                hopperContainer.setItem(i,)
                            }
                            newItem.amount = 1
                            container.setItem(0, newItem)
                            entity.runCommand(`replaceitem entity @s slot.weapon.offhand 0 ${newItem?.typeId}`)
                            if (racoAPI.itemIsBlock(block, newItem)){
                                entity.setProperty('vtng_rt:type', 1)
                            } else entity.setProperty('vtng_rt:type', 0)
                        }
                        shouldBreak = true;
                        break
                    }
                }
            }
        }
        if (shouldBreak) break
    }
    if (block.permutation.getState('vtng_rt:on') == false && on){
        const withoutItems = [
            "daylight_detector",
            "door",
            "repeater",
            "lever",
            "fence_gate",
            "candle"
        ]
        const withItems = {
            "bone_meal":[
                "wheat",
                "carrots",
                "potatoes",
                "beetroot"
            ],
            "flint_and_steel":["candle", "campfire"],
            "_shovel":["campfire", "dirt"],
            "_hoe":["dirt", "grass_block"],
            "_axe":["_log"]
        }
        const frontBlock = block[racoAPI.blockFaceToDirection(direction)]()
        const item = container?.getItem(0)
        if (item){
            if (userItemIsBlock(block, item)){
                if (frontBlock?.isAir){
                    entity.runCommand(`setblock ${frontBlock.x} ${frontBlock.y} ${frontBlock.z} ${item?.typeId}`)
                    if (item?.amount > 1){
                        item.amount = item.amount-1
                        container.setItem(0, item)
                    } else if (item?.amount == 1){
                        container.setItem(0,)
                        entity.runCommand(`replaceitem entity @s slot.weapon.offhand 0 air`)
                    }
                }
            } else if (racoAPI.includesAny(item?.typeId, Object.keys(withItems))){
            const index = racoAPI.includesAnyIndex(item?.typeId, Object.keys(withItems))
            const blocks = withItems[Object.keys(withItems)[index]]
            if (racoAPI.includesAny(frontBlock?.typeId, blocks)){
                    interactWithBlock(entity, 0, frontBlock)
                }
            }
        } else {
            if (racoAPI.includesAny(frontBlock?.typeId, withoutItems)){
                interactWithBlock(entity, 0, frontBlock)
            }
        }
    }
    if (block.permutation.getState('vtng_rt:on') != on && !block?.isAir) racoAPI.setPermutation(block, 'vtng_rt:on', on)
}
export function placerTick(block){
    const on = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'], true) ?? false;
    if (block.permutation.getState('vtng_rt:on') == false && on){
        const frontBlock = block[toFace[block.permutation.getState('minecraft:facing_direction')]]() //AAAAAAAAAs
        if (frontBlock?.isAir){
            const faces = [
                'north',
                'south',
                'west',
                'east',
                'above'
            ]
            hoppers: for (const face of faces){
                const faceBlock = block[face]()
                if (faceBlock?.typeId == 'minecraft:hopper' && racoAPI.numToDirection(faceBlock.permutation.getState('facing_direction')) == racoAPI.invertFace(face) || (face == 'above' && faceBlock.permutation.getState('facing_direction') < 2)){
                    const container = faceBlock.getComponent('inventory')?.container
                    if (container){
                        for (let i = 0; i < container.size; i++){
                            const thisItem = container.getItem(i)
                            if (thisItem){
                                if (racoAPI.placerItemIsBlock(block, thisItem)){
                                    if (thisItem.typeId.includes('button') && thisItem.typeId.includes('minecraft')) {
                                        frontBlock.dimension.runCommand(`setblock ${frontBlock.x} ${frontBlock.y} ${frontBlock.z} ${thisItem?.typeId} ["facing_direction"=1]`)
                                    } else if (thisItem.typeId == 'minecraft:lever') {
                                        frontBlock.dimension.runCommand(`setblock ${frontBlock.x} ${frontBlock.y} ${frontBlock.z} ${thisItem?.typeId} ["lever_direction"="up_north_south"]`)
                                    } else frontBlock.setType(thisItem?.typeId)
                                    racoAPI.clearItem(container, i, 1)
                                    break hoppers
                                }
                            }
                        }
                    }
                } else block.dimension.playSound('random.click', block.center(), {pitch: 1, volume: 1}), block.dimension.spawnParticle(`vtng_rt:crafter_smoke_${racoAPI.invertFace(block.permutation.getState('minecraft:facing_direction'))}`, block.center());
            }
        } else block.dimension.playSound('random.click', block.center(), {pitch: 1, volume: 1}), block.dimension.spawnParticle(`vtng_rt:crafter_smoke_${racoAPI.invertFace(block.permutation.getState('minecraft:facing_direction'))}`, block.center());
    }
    if (block.permutation.getState('vtng_rt:on') != on) racoAPI.setPermutation(block, 'vtng_rt:on', on)
}
export function sawTick(block){
    const on = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'], true) ?? false;
    if (block.permutation.getState('vtng_rt:on') == false && on){
        let visitedBlocks = []
        veinRecursion(block)
        function veinRecursion(block){
            if (visitedBlocks.length > 80) return
            if (!visitedBlocks?.includes(JSON.stringify(block.location))){
                visitedBlocks?.push(JSON.stringify(block.location))
                if (block.typeId.includes('log')){
                    block.dimension.runCommand(`fill ${block.x-5} ${block.y} ${block.z-5} ${block.x+5} ${block.y+5} ${block.z+5} air replace leaves`)
                    block.dimension.runCommand(`setblock ${racoAPI.locToCommand(block)} air destroy`)
                }
                const faces = [
                    'north',
                    'south',
                    'west',
                    'east',
                    'above',
                    'below'
                ]
                for (const face of faces){
                    const thisBlock = block[face]()
                    if (thisBlock?.typeId?.includes('log')){
                        block.dimension.playSound('block.stonecutter.use', block.center(), {pitch: 1, volume: 1})
                        veinRecursion(thisBlock)
                    }
                }
            }
        }
    }
    if (block.permutation.getState('vtng_rt:on') != on) racoAPI.setPermutation(block, 'vtng_rt:on', on)
}

export function igniterBlockFaceToDirection(face){
    if (face.toLowerCase() == 'up') return 'below'; else
    if (face.toLowerCase() == 'down') return 'above'; else
    if (face.toLowerCase() == 'north') return 'north'; else
    if (face.toLowerCase() == 'south') return 'south'; else
    if (face.toLowerCase() == 'west') return 'west'; else
    if (face.toLowerCase() == 'east') return 'east'; else return (face)
 }

export function igniterTick(block){
    const on = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'], true) ?? false;
    if (block.permutation.getState('vtng_rt:on') == false && on){
        block.dimension.playSound('fire.ignite', block.center(), {pitch: 1, volume: 1})
        const faceBlock = block[igniterBlockFaceToDirection(block.permutation.getState('minecraft:facing_direction'))]();
        if (faceBlock.isAir) faceBlock.setType("minecraft:fire");
    } else 
    if (block.permutation.getState('vtng_rt:on') == true && !on){
        block.dimension.playSound('extinguish.candle', block.center(), {pitch: 1, volume: 1})
        const faceBlock = block[igniterBlockFaceToDirection(block.permutation.getState('minecraft:facing_direction'))]()
        if (faceBlock?.typeId == 'minecraft:fire') faceBlock.setType("minecraft:air")
    }
    if (block.permutation.getState('vtng_rt:on') != on) racoAPI.setPermutation(block, 'vtng_rt:on', on)
}


function userItemIsBlock(block, item) {
    {
        try {
            if (block.dimension.runCommand(`setblock ${block.x} -64 ${block.z} ${item?.typeId}`).successCount > 0) {
                block.dimension.runCommand(`setblock ${block.x} -64 ${block.z} bedrock`)
                return true;
            } else {
                return false;
            }
        } catch (error) {
            return false;
        }
    }
}
mc.world.afterEvents.playerPlaceBlock.subscribe((data)=>{
    const block = data.block
    const player = data.player
    if (block.typeId == 'vtng_rt:user'){
        const entity = block.dimension.spawnEntity('vtng_rt:user_entity', block.center())
        entity.setProperty('vtng_rt:cardinal_rotation', racoAPI.invertUpDown(racoAPI.invertFace(block.permutation.getState('minecraft:facing_direction')))) 
    }
})

export function filteredObserverTick(block){
    const frontBlock = block[block.permutation.getState('minecraft:cardinal_direction')]()
    if (block.permutation.getState('vtng_rt:on') == false){
        if (frontBlock.typeId == mc.world.getDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)},filter`) || (!mc.world.getDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)},filter`) && !frontBlock.isAir)){
            racoAPI.setPermutation(block, 'vtng_rt:on', true)
            
            const sendBlock = block[block.permutation.getState('minecraft:cardinal_direction')](-1)
            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}]`)
                }
            }
        }
    } else {
        if (frontBlock.typeId != mc.world.getDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)},filter`) && mc.world.getDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)},filter`) || frontBlock.isAir){
            racoAPI.setPermutation(block, 'vtng_rt:on', false)
        }
    }
}
export function filteredObserverInteract(player, block){
    const item = player.getComponent('equippable')?.getEquipment('Mainhand')
    if (player.isSneaking){
        if (!item){
            if (mc.world.getDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)},filter`)){
                mc.world.setDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)},filter`, undefined) 
                player.runCommand(`title @s actionbar filter removed`)
            }
        }
    } else {
        if (item){
            if (racoAPI.itemIsBlock(block, item)){
                mc.world.setDynamicProperty(`${block.dimension.id},${JSON.stringify(block.location)},filter`, item?.typeId)
                player.runCommand(`title @s actionbar filter set to: §9${racoAPI.transformKey(item.typeId)}`)
            } else player.runCommand(`title @s actionbar §4this item is not a block`)
        }
    }
}

export function elevatorTick(block) {
    const on = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'], true) ?? false ? 1 : 0, p = block.dimension.getEntities({type: 'minecraft:player', location: block.above().center(), maxDistance: 0.7, closest: 1})[0]
    if (on) {
        if (p?.isSneaking && !p?.hasTag('elevatorandokk')) eRec(block, 'below', 0, p), p.addTag('elevatorandokk')
        else if (p?.isJumping && !p?.hasTag('elevatorandokk')) eRec(block, 'above', 0, p), p.addTag('elevatorandokk')
        else if (!p?.isSneaking && !p?.isJumping && p?.hasTag('elevatorandokk')) p.removeTag('elevatorandokk')
    }
    if (block.permutation.getState('vtng_rt:on') != on) racoAPI.setPermutation(block, 'vtng_rt:on', on)
    function eRec(b, d, a, p) { if (a < 50 && b[d]()?.typeId != 'minecraft:bedrock') b[d]()?.typeId != 'vtng_rt:elevator' || !b[d]()?.permutation.getState('vtng_rt:on') ? eRec(b[d](), d, a + 1, p) : p.teleport(b[d]().above().center()), block.dimension.playSound('mob.shulker.teleport', p.location, {volume: 0.2, pitch: 1.3}) }
}


export function itemElevatorTick(block){
    if (block.permutation.getState('vtng_rt:on') == false){



        const items = block.dimension.getEntities({type:'minecraft:item', location:block.center(), maxDistance:0.3})
        if (items?.length > 0){
            racoAPI.setPermutation(block, 'vtng_rt:on', true)
        } else 
        racoAPI.setPermutation(block, 'vtng_rt:on', false)
        for (const thisItemEntity of items){
            thisItemEntity.teleport({x:block.center().x, y:block.center().y+1.2, z:block.center().z})
        }


        
        const faces = [
            'north',
            'south',
            'west',
            'east',
            'above'
        ]
        hoppers: for (const face of faces){
            const faceBlock = block[face]()
            if (faceBlock?.typeId == 'minecraft:hopper' && racoAPI.numToDirection(faceBlock.permutation.getState('facing_direction')) == racoAPI.invertFace(face)){
                const container = faceBlock.getComponent('inventory')?.container
                if (container){
                    for (let i = 0; i < container.size; i++){
                        const thisItem = container.getItem(i)
                        if (thisItem){
                            thisItem.amount = 1
                            const dropItem = block.dimension.spawnItem(thisItem, {x:block.center().x, y:block.center().y+0.2, z:block.center().z})
                            dropItem.teleport({x:block.center().x, y:block.center().y+0.2, z:block.center().z})
                            racoAPI.clearItem(container, i, 1)
                            break hoppers
                        }
                    }
                }
            }
        }
    } else 
    racoAPI.setPermutation(block, 'vtng_rt:on', false)
}

export function harvesterTick(block){
    const on = hasRedstonePower(block, ['north', 'south', 'west', 'east', 'below'], false) ?? false;
    const frontBlock = block[block.permutation.getState('minecraft:cardinal_direction')]()
    const cropBlocks = [
        'minecraft:potatoes',
        'minecraft:wheat',
        'minecraft:beetroot',
        'minecraft:carrots'
    ]
    if (block.permutation.getState('vtng_rt:on') == false && on){
        block.dimension.playSound('mob.bee.sting', block.center(), {pitch: 1, volume: 1})
        if (cropBlocks.includes(frontBlock?.typeId)){
            if (frontBlock?.permutation.getState('growth') >= 2)
            block.dimension.runCommand(`setblock ${frontBlock.x} ${frontBlock.y} ${frontBlock.z} ${frontBlock.typeId} destroy`)
        }
    }
    if (on && block.permutation.getState('vtng_rt:on') == true){
        if (frontBlock?.permutation.getState('growth') >= 2)
            block.dimension.runCommand(`setblock ${frontBlock.x} ${frontBlock.y} ${frontBlock.z} ${frontBlock.typeId} destroy`)
    }
    if (block.permutation.getState('vtng_rt:on') != on) racoAPI.setPermutation(block, 'vtng_rt:on', on)
}

export function trashCanTick(block){
    const faces = [
        'north',
        'south',
        'west',
        'east',
        'above'
    ]
    hoppers: for (const face of faces){
        const faceBlock = block[face]()
        if (faceBlock?.typeId == 'minecraft:hopper' && racoAPI.numToDirection(faceBlock.permutation.getState('facing_direction')) == racoAPI.invertFace(face) || (face == 'above' && faceBlock.permutation.getState('facing_direction') < 2)){
            const container = faceBlock.getComponent('inventory')?.container
            if (container){
                for (let i = 0; i < container.size; i++){
                    const thisItem = container.getItem(i)
                    if (thisItem){
                        racoAPI.clearItem(container, i, 1)
                        block.dimension.playSound('random.fizz', block.center(), {pitch: 9, volume: 1})
                    }
                }
            }
        }
    }
}


export function IFLampTick(block){
    const on = hasRedstonePower(block, ['above','below','north','south','west','east'], false)
    if (on){
        if (block.permutation.getState('vtng_rt:on') == false) racoAPI.setPermutation(block, 'vtng_rt:on', true)
        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}]`)
                }
            }
        }
    } else {
        let isOn = false
        IfValid(block, racoAPI.blockFaceToDirection(block.permutation.getState('minecraft:facing_direction')), 0, block)
        function IfValid(block, direction, depth, origin) {
            if (depth < 50) {
                const nextBlock = block[racoAPI.invertUpDown(direction)]?.()
                if (nextBlock && !racoAPI.isSolid(nextBlock) &&
                    (nextBlock?.typeId !== 'vtng_rt:if_lamp')) {
                        //nextBlock.dimension.spawnParticle('minecraft:basic_flame_particle', nextBlock.center())
                        IfValid(nextBlock, direction, depth + 1, origin)
                } else {
                    if (nextBlock?.typeId == 'vtng_rt:if_lamp' && hasRedstonePower(nextBlock, ['above','below','north','south','west','east'], true)){
                        const direction = racoAPI.blockFaceToDirection(origin.permutation.getState('minecraft:facing_direction'))
                        const nextDirection = racoAPI.blockFaceToDirection(nextBlock.permutation.getState('minecraft:facing_direction'))
                        if (direction == racoAPI.invertFace(nextDirection)){
                            isOn = true
                            if (origin.permutation.getState('vtng_rt:on') == false){
                                nextBlock.dimension.spawnParticle('vtng_rt:redstone_out', nextBlock.center())
                                origin.dimension.playSound('hit.amethyst_block', origin.center(), {pitch: 2.1, volume: 9999999})
                                origin.dimension.spawnParticle('vtng_rt:redstone_inp', origin.center())
                            }
                        }
                        //origin.dimension.spawnParticle('minecraft:basic_flame_particle', origin.center())
                        //console.warn(direction, nextDirection)
                        //&& racoAPI.blockFaceToDirection(nextBlock.permutation.getState('minecraft:facing_direction')) == racoAPI.invertFace(racoAPI.blockFaceToDirection(block.permutation.getState('minecraft:facing_direction')
                    }
                }
            }
        }
        if (block.permutation.getState('vtng_rt:on') != isOn) racoAPI.setPermutation(block, 'vtng_rt:on', isOn);
        if (isOn){
            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}]`)
                    }
                }
            }
        };
    }
    
}
export function debuggerTick(block){
    const on = getRedstonePower(block, ['above','below','north','south','west','east'], true) > 0 ? getRedstonePower(block, ['above','below','north','south','west','east'], true) : 0
    racoAPI.setPermutation(block, 'vtng_rt:on', on)
}



/*export function rDisplayInteract(player, block){
    const item = player?.getComponent('equippable')?.getEquipment("Mainhand")
    if (item?.typeId == 'vtng_rt:pliers'){
        const arrays = {
            "vtng_rt:number": ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
            "vtng_rt:letters": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"],
            "vtng_rt:letters2": ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
            "vtng_rt:symbols": ["-", ":", "!", "/", "#", "?"]
        }
        const allArray = combineAllElements(arrays)
        const displayForm = new mcui.ModalFormData()
        .title("Redstone Display")
        .dropdown("Select Caractere:", allArray, 0)
        .submitButton('Select')
        .show(player).then((form)=>{
            const stateSelected = form.formValues[0]
            const digitos = separarDigitos(stateSelected)
            racoAPI.setPermutation(block, 'vtng_rt:unidade', digitos.unidade)
            racoAPI.setPermutation(block, 'vtng_rt:dezena', digitos.dezena)
        })
    }
}*/

export function rDisplayInteract(player, block){
    const item = player?.getComponent('equippable')?.getEquipment("Mainhand")
    if (item?.typeId == 'vtng_rt:pliers'){
        const arrays = {
            "vtng_rt:number": ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
            "vtng_rt:letters": ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"],
            "vtng_rt:letters2": ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
            "vtng_rt:symbols": ["-", ":", "!", "/", "#", "?"]
        }
        const allArray = combineAllElements(arrays)
        const displayForm = new mcui.ModalFormData()
        .title("Redstone Display")
        .dropdown("Select Caractere:", allArray, 0)
        .submitButton('Select')
        .show(player).then((form)=>{
            const stateSelected = form.formValues[0]
            const digitos = separarDigitos(stateSelected)
            racoAPI.setPermutation(block, 'vtng_rt:unidade', digitos.unidade)
            racoAPI.setPermutation(block, 'vtng_rt:dezena', digitos.dezena)
        })
    }
}

export function rDisplayTick(block){
    const on = hasRedstonePower(block, ['above','below','north','south','west','east'], true) ? hasRedstonePower(block, ['above','below','north','south','west','east'], true) : false
    racoAPI.setPermutation(block, 'vtng_rt:on', on)
}

function combineAllElements(arrays) {
    return Object.values(arrays).flat();
}
function findArrayName(element, arrays) {
    for (const [key, values] of Object.entries(arrays)) {
        if (values.includes(element)) {
            return key;
        }
    }
    return null; // Retorna null se o elemento não estiver em nenhuma array
}
function separarDigitos(numero) {
    const unidade = numero % 10;
    const dezena = Math.floor((numero % 100) / 10);
    const centena = Math.floor(numero / 100);
    
    return { unidade, dezena, centena };
}

const toFace = { 'north': 'north', 'south': 'south', 'east': 'east',  'west': 'west', 'up': 'below', 'down': 'above' };