import { world, system, ItemStack, BlockPermutation, MolangVariableMap } from "@minecraft/server";
import { fence_Manager } from './fence_Manager'

world.beforeEvents.worldInitialize.subscribe(initEvent => {

    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:reset_top', {
        onPlayerDestroy: e => {
            const block = e.block
            block.above(1).setPermutation(BlockPermutation.resolve('minecraft:air'))
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:reset_bottom', {
        onPlayerDestroy: e => {
            const block = e.block
            block.below(1).setPermutation(BlockPermutation.resolve('minecraft:air'))
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:fence_place', {
        onPlace: e => {
            const block = e.block
            block.setPermutation(block.permutation.withState('lv_zo:on_placed', true))
        },
    });
    //Slab Related
    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:grass_to_dirt', {
        onTick: e => {
            const block = e.block
            if (block.below(1).typeId == 'minecraft:grass') {
                block.below(1).setPermutation(BlockPermutation.resolve("minecraft:dirt"))
            }
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:double_slab', {
        onPlayerInteract: e => {
            const block = e.block
            const player = e.player
            const item = e.player.getComponent('equippable').getEquipment('Mainhand')
            double_slab(block, item, player, "corrupted")
        },
    });
    //Doors
    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:open', {
        onPlayerInteract: e => {
            const block = e.block
            const player = e.player
            const item = e.player.getComponent('equippable').getEquipment('Mainhand')
            if (block.hasTag('lv_zo:trapdoor')) {
                if (block.permutation.getState('lv_zo:is_open') == false) {
                    block.setPermutation(block.permutation.withState('lv_zo:is_open', true))
                    block.dimension.playSound('open.wooden_trapdoor', block.center())
                }
                else if (block.permutation.getState('lv_zo:is_open') == true) {
                    block.setPermutation(block.permutation.withState('lv_zo:is_open', false))
                    block.dimension.playSound('close.wooden_trapdoor', block.center())
                }
            }
            if (block.hasTag('lv_zo:fence_gate')) {
                if (block.permutation.getState('lv_zo:is_open') == false) {
                    block.setPermutation(block.permutation.withState('lv_zo:is_open', true))
                    block.dimension.playSound('open.fence_gate', block.center())
                }
                else if (block.permutation.getState('lv_zo:is_open') == true) {
                    block.setPermutation(block.permutation.withState('lv_zo:is_open', false))
                    block.dimension.playSound('close.fence_gate', block.center())
                }
            }
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:door_open', {
        onPlayerInteract: e => {
            const block = e.block
            const player = e.player
            const item = e.player.getComponent('equippable').getEquipment('Mainhand')
            if (block.hasTag('lv_zo:door')) {
                if (block.permutation.getState('lv_zo:is_open') == false) {
                    door_open_close(block, true)
                    if (!(block.hasTag("lv_zo:door_top"))) {
                        door_open_close(block.above(1), true)
                    }
                    if (block.hasTag("lv_zo:door_top")) {
                        door_open_close(block.below(1), true)
                    }
                }
            }

        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:door_close', {
        onPlayerInteract: e => {
            const block = e.block
            const player = e.player
            const item = e.player.getComponent('equippable').getEquipment('Mainhand')
            if (block.hasTag('lv_zo:door')) {
                if (block.permutation.getState('lv_zo:is_open') == true) {
                    door_open_close(block, false)
                    if (!(block.hasTag("lv_zo:door_top"))) {
                        door_open_close(block.above(1), false)
                    }
                    if (block.hasTag("lv_zo:door_top")) {
                        door_open_close(block.below(1), false)
                    }
                }
            }

        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('lv_zo:door_place', {
        onPlace: e => {
            const block = e.block

            switch (block.typeId) {
                case "lv_zo:corrupted_door_bottom":
                    block.above(1).setPermutation(BlockPermutation.resolve("lv_zo:corrupted_door_top"))
                    block.above(1).setPermutation(block.above(1).permutation.withState('minecraft:cardinal_direction', block.permutation.getState('minecraft:cardinal_direction')))
                    break;

                case "lv_zo:corrupted_door_bottom_flipped":

                    block.above(1).setPermutation(BlockPermutation.resolve("lv_zo:corrupted_door_top_flipped"))
                    block.above(1).setPermutation(block.above(1).permutation.withState('minecraft:cardinal_direction', block.permutation.getState('minecraft:cardinal_direction')))
                    break;
            }
        },
    });
});


//Decrement stack
export function decrementstack(item, user) {
    if (!(item?.typeId == undefined)) {
        if (item.amount > 1) {
            item.amount--;
            user.getComponent('equippable').setEquipment('Mainhand', item)
        }
        else if (item.amount === 1) {
            user.getComponent('equippable').setEquipment('Mainhand', undefined)
        }
    }
}

function double_slab(block, item, player, type) {
    let req = "lv_zo:" + type + "_slab"
    if (block.typeId == req && item?.typeId == req) {
        block.dimension.playSound('use.wood', block.center())
        decrementstack(item, player)
        block.setPermutation(BlockPermutation.resolve("lv_zo:" + type + "_double_slab"))
    }
}

export function adjustItemDamage(playerEquip, itemStack, damageToAdd, slot) {
    const durabilityComp = itemStack.getComponent('minecraft:durability');
    if (!durabilityComp) return;
    if (durabilityComp.damage === durabilityComp.maxDurability && playerEquip) {
        playerEquip.setItem(slot, undefined);
    } else {
        durabilityComp.damage = Math.min(durabilityComp.damage + damageToAdd, durabilityComp.maxDurability);
        if (durabilityComp.damage === durabilityComp.maxDurability) {
            playerEquip.setItem(slot, undefined);
        } else {
            playerEquip.setItem(slot, itemStack);
        }
    }
}

function door_open_close(block, istrue) {
    block.setPermutation(block.permutation.withState('lv_zo:is_open', istrue))
    if (!(block.hasTag('lv_zo:door_top')) && istrue == true) {
        block.dimension.playSound('open.wooden_door', block.center())
    }
    if (!(block.hasTag('lv_zo:door_top')) && istrue == false) {
        block.dimension.playSound('close.wooden_door', block.center())
    }

}
world.afterEvents.playerBreakBlock.subscribe((data) => {
    fence_Manager.updateFencesAround(data.block)
})
world.afterEvents.playerPlaceBlock.subscribe((data) => {
    fence_Manager.updateFencesAround(data.block)
})
