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

export function adjRepeaterInteract(player, block){
    const item = player?.getComponent('equippable')?.getEquipment("Mainhand")
    player.runCommand(`scoreboard objectives add Delay dummy Delay`)
    block.dimension.runCommand(`scoreboard players add "${block.dimension.id},${block.x},${block.y},${block.z}" Delay 0`)
    if (item?.typeId == 'vtng_rt:pliers'){
        const Delay = mc.world.scoreboard.getObjective('Delay')
        const currentScore = Delay.getScore(`${block.dimension.id},${block.x},${block.y},${block.z}`)
        const DelayForm = new mcui.ModalFormData()
        .title("Adjustable Pulse Repeater")
        .slider("Set a delay (ticks)", 0, 500, 1, currentScore) 
        .submitButton('Confirm')
        .show(player)?.then((form)=>{
            if (!form.canceled){
                if (form.formValues[0] > 0){
                    block.dimension.runCommand(`scoreboard players set "${block.dimension.id},${block.x},${block.y},${block.z}" Delay ${form.formValues[0]}`)       
                    function separarDigitos(numero) {
                        const unidade = numero % 10;
                        const dezena = Math.floor((numero % 100) / 10);
                        const centena = Math.floor(numero / 100);
                        
                        return { unidade, dezena, centena };
                    }
                    function setNum(value){
                        try {
                            racoAPI.setPermutation(block, `vtng_rt:unidade`, separarDigitos(value)?.unidade)
                            racoAPI.setPermutation(block, `vtng_rt:dezena`, separarDigitos(value)?.dezena)
                            racoAPI.setPermutation(block, `vtng_rt:centena`, separarDigitos(value)?.centena)
                        } catch(error){}
                    }
                    setNum(form.formValues[0])
                }
            }
        })
    }
}
export function adjRepeaterTick(block){
    const on = hasRedstonePower(block, [racoAPI.invertFace(block.permutation.getState('minecraft:cardinal_direction'))], true)
    const property = mc.world.getDynamicProperty(`vtng_rt:${block.dimension.id},${JSON.stringify(block.location)},delay`)
    if (on && !block.permutation.getState('vtng_rt:on2')){
        racoAPI.setPermutation(block, 'vtng_rt:on2', true)
        mc.world.setDynamicProperty(`vtng_rt:${block.dimension.id},${JSON.stringify(block.location)},delay`, cduToNum(block.permutation.getState('vtng_rt:centena'), block.permutation.getState('vtng_rt:dezena'), block.permutation.getState('vtng_rt:unidade')))
    }
    if (block.permutation.getState('vtng_rt:on2')){
        if (property > 0){
            mc.world.setDynamicProperty(`vtng_rt:${block.dimension.id},${JSON.stringify(block.location)},delay`, property-1)
        }  else if (property == 0){
            mc.world.setDynamicProperty(`vtng_rt:${block.dimension.id},${JSON.stringify(block.location)},delay`, undefined)
            racoAPI.setPermutation(block, 'vtng_rt:on', true)
            const sendBlock = block[block.permutation.getState('minecraft:cardinal_direction')]()
            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}]`)
                }
            }
            mc.system.runTimeout(()=>{
                racoAPI.setPermutation(block, 'vtng_rt:on', false)
                racoAPI.setPermutation(block, 'vtng_rt:on2', false)
            },5)
        }
    }
}
function cduToNum(c, d, u){
    const c1 = c*100
    const d1 = d*10
    const u1 = u
    return (c1+d1+u1)
  }



export function crossTick(block){
    const on = hasRedstonePower(block, ['west','east'], true) ? hasRedstonePower(block, ['west','east'], true) : false
    const on2 = hasRedstonePower(block, ['north','south'], true) ? hasRedstonePower(block, ['north','south'], true) : false
    if (block.permutation.getState('vtng_rt:on') != on) racoAPI.setPermutation(block, 'vtng_rt:on', on)
    if (block.permutation.getState('vtng_rt:on2') != on2) racoAPI.setPermutation(block, 'vtng_rt:on2', on2)
        
    if (on2){
        const faces = [
            block.north(),
            block.south()
        ]
        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 (on){
        const faces = [
            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 toggleTick(block){
    const currentOn = hasRedstonePower(block, [racoAPI.invertFace(block.permutation.getState('minecraft:cardinal_direction'))], true) ? hasRedstonePower(block, [racoAPI.invertFace(block.permutation.getState('minecraft:cardinal_direction'))], true) : false
    
    if (block.permutation.getState('vtng_rt:previous_on') == false && currentOn){
        racoAPI.setPermutation(block, 'vtng_rt:on', !block.permutation.getState("vtng_rt:on"))
    }
    if (block.permutation.getState("vtng_rt:on")){
        const sendBlock = block[block.permutation.getState('minecraft:cardinal_direction')]()
        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}]`)
            }
        }
    }

    racoAPI.setPermutation(block, 'vtng_rt:previous_on', currentOn)
}

export function clockInteract(player, block){
    if (block.permutation.getState('vtng_rt:delay') < 8){
        racoAPI.setPermutation(block, 'vtng_rt:delay', block.permutation.getState('vtng_rt:delay')+1)
        block.dimension.playSound('random.click', block.center(), {pitch: 0.2, volume: 1})
    } else if (block.permutation.getState('vtng_rt:delay') == 8){
        racoAPI.setPermutation(block, 'vtng_rt:delay', 1)
        block.dimension.playSound('random.click', block.center(), {pitch: 0.2, volume: 1})
    }
    player.runCommand(`title @s actionbar Delay: ${2**(block.permutation.getState("vtng_rt:delay")-1)} Ticks`)
}

export function clockTick(block){
    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}]`)
            }
        }
    }
    mc.system.runTimeout(()=>{
        block?.dimension?.spawnParticle('vtng_rt:clock_particle', {x:block?.center()?.x, y:block?.y+(2.01/16), z:block?.center()?.z})
    },2)
    //racoAPI.setPermutation(block, 'vtng_rt:on', false)
    //mc.system.run(()=>{
    //    racoAPI.setPermutation(block, 'vtng_rt:on', true)
    //    mc.system.runTimeout(()=>{
    //        try {
    //            if (block)
    //            racoAPI.setPermutation(block, 'vtng_rt:on', false)
    //        } catch(error){}
    //    },3)
    //})
}


export function counterInteract(player, block){
    if (block.permutation.getState('vtng_rt:limit') < 9){
        racoAPI.setPermutation(block, 'vtng_rt:limit', block.permutation.getState('vtng_rt:limit')+1)
        block.dimension.playSound('random.click', block.center(), {pitch: 0.2, volume: 1})
    } else if (block.permutation.getState('vtng_rt:limit') == 9){
        block.dimension.playSound('random.click', block.center(), {pitch: 0.2, volume: 1})
        racoAPI.setPermutation(block, 'vtng_rt:limit', 0)
        racoAPI.setPermutation(block, 'vtng_rt:numbers', 0)
    }
}
export function counterTick(block){
    const currentOn = hasRedstonePower(block, ['west','east', 'north', 'south'], true) ? hasRedstonePower(block, ['west','east', 'north', 'south'], true) : false
    
    if (block.permutation.getState('vtng_rt:previous_on') == false && currentOn){
        if (block.permutation.getState('vtng_rt:numbers') < block.permutation.getState('vtng_rt:limit')){
            racoAPI.setPermutation(block, 'vtng_rt:numbers', block.permutation.getState('vtng_rt:numbers')+1)
        }
    }
    if (block.permutation.getState('vtng_rt:numbers') == block.permutation.getState('vtng_rt:limit')){
        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}]`)
                }
            }
        }
        mc.system.run(()=>{
            racoAPI.setPermutation(block, 'vtng_rt:on', true)
            mc.system.runTimeout(()=>{
                try {
                    if (block)
                    racoAPI.setPermutation(block, 'vtng_rt:on', false)
                    racoAPI.setPermutation(block, 'vtng_rt:numbers', 0)
                } catch(error){}
            },3)
        })
    }

    racoAPI.setPermutation(block, 'vtng_rt:previous_on', currentOn)
}

export function randomizerTick(block){
    const on = hasRedstonePower(block, [block.permutation.getState('minecraft:cardinal_direction')], true) ? hasRedstonePower(block, [block.permutation.getState('minecraft:cardinal_direction')], true) : false
    if (block.permutation.getState("vtng_rt:on") == 'false'){
        if (on){
            const ss = [
                'north',
                'west',
                'east'
            ]
            racoAPI.setPermutation(block, 'vtng_rt:on', ss[randomIndex(ss)])
        }
    } else {
        if (!on){
            racoAPI.setPermutation(block, 'vtng_rt:on', 'false')
        }
    }
    if (block.permutation.getState("vtng_rt:on") != 'false'){
        const sendBlock = block[trueFace(racoAPI.invertFace(block.permutation.getState('minecraft:cardinal_direction')), block.permutation.getState("vtng_rt:on"))]()
        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}]`)
            }
        }
    }
}
function randomIndex(array) {
    return Math.floor(Math.random() * array.length);
}
function trueFace(currentDirection, relativeDirection) {
    // Mapeia as direções para valores numéricos
    const directions = ["north", "east", "south", "west"];
    
    // Obtém os índices das direções fornecidas
    const currentIndex = directions.indexOf(currentDirection.toLowerCase());
    const relativeIndex = directions.indexOf(relativeDirection.toLowerCase());
    
    if (currentIndex === -1 || relativeIndex === -1) {
        throw new Error("Direção inválida. Use: 'north', 'south', 'west' ou 'east'.");
    }
    
    // Calcula o índice absoluto usando aritmética modular
    const absoluteIndex = (currentIndex + relativeIndex) % directions.length;
    
    // Retorna a direção absoluta
    return directions[absoluteIndex];
}


export function pulserInteract(player, block){
    if (block.permutation.getState('vtng_rt:delay') < 16){
        block.dimension.playSound('random.click', block.center(), {pitch: 0.2, volume: 1})
        racoAPI.setPermutation(block, 'vtng_rt:delay', block.permutation.getState('vtng_rt:delay')+5)
    } else if (block.permutation.getState('vtng_rt:delay') == 16){
        block.dimension.playSound('random.click', block.center(), {pitch: 0.2, volume: 1})
        racoAPI.setPermutation(block, 'vtng_rt:delay', 1)
    }
}
export function pulserTick(block){
    //console.warn(block.permutation.getState('vtng_rt:seilaporra'))
    const on = hasRedstonePower(block, [block.permutation.getState('minecraft:cardinal_direction')], true) ? hasRedstonePower(block, [block.permutation.getState('minecraft:cardinal_direction')], true) : false
    if (block.permutation.getState('vtng_rt:previous_on') == false && on && block.permutation.getState('vtng_rt:on') == false){
        racoAPI.setPermutation(block, 'vtng_rt:previous_on', true)
        racoAPI.setPermutation(block, 'vtng_rt:on', true)
        racoAPI.setPermutation(block, 'vtng_rt:seilaporra', block.permutation.getState("vtng_rt:delay"))
        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 (block.permutation.getState('vtng_rt:seilaporra') > 1){
        racoAPI.setPermutation(block, 'vtng_rt:seilaporra', block.permutation.getState('vtng_rt:seilaporra')-1)
        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 (block.permutation.getState('vtng_rt:seilaporra') == 1){
        racoAPI.setPermutation(block, 'vtng_rt:seilaporra', 1)
        if (!on) racoAPI.setPermutation(block, 'vtng_rt:previous_on', false)
        racoAPI.setPermutation(block, 'vtng_rt:on', false)
    }
    if (block.permutation.getState('vtng_rt:previous_on') == true && !on){
        racoAPI.setPermutation(block, 'vtng_rt:previous_on', false)
    }
}