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

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

    initEvent.blockComponentRegistry.registerCustomComponent('bumble:reset_top', {
        onPlayerDestroy: e => {
            const block = e.block
            block.above(1).setPermutation(BlockPermutation.resolve('minecraft:air'))
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('bumble:reset_bottom', {
        onPlayerDestroy: e => {
            const block = e.block
            block.below(1).setPermutation(BlockPermutation.resolve('minecraft:air'))
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('bumble:fence_place', {
        onPlace: e => {
            const block = e.block
            block.setPermutation(block.permutation.withState('bumble:on_placed', true))
        },
    });
    //Slab Related
    initEvent.blockComponentRegistry.registerCustomComponent('bumble: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('bumble: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, "template")
        },
    });
    //Doors
    initEvent.blockComponentRegistry.registerCustomComponent('bumble:open', {
        onPlayerInteract: e => {
            const block = e.block
            const player = e.player
            const item = e.player.getComponent('equippable').getEquipment('Mainhand')
            if (block.hasTag('bumble:trapdoor')) {
                if (block.permutation.getState('bumble:is_open') == false) {
                    block.setPermutation(block.permutation.withState('bumble:is_open', true))
                    block.dimension.playSound('open.wooden_trapdoor', block.center())
                }
                else if (block.permutation.getState('bumble:is_open') == true) {
                    block.setPermutation(block.permutation.withState('bumble:is_open', false))
                    block.dimension.playSound('close.wooden_trapdoor', block.center())
                }
            }
            if (block.hasTag('bumble:fence_gate')) {
                if (block.permutation.getState('bumble:is_open') == false) {
                    block.setPermutation(block.permutation.withState('bumble:is_open', true))
                    block.dimension.playSound('open.fence_gate', block.center())
                }
                else if (block.permutation.getState('bumble:is_open') == true) {
                    block.setPermutation(block.permutation.withState('bumble:is_open', false))
                    block.dimension.playSound('close.fence_gate', block.center())
                }
            }
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('bumble:door_open', {
        onPlayerInteract: e => {
            const block = e.block
            const player = e.player
            const item = e.player.getComponent('equippable').getEquipment('Mainhand')
            if (block.hasTag('bumble:door')) {
                if (block.permutation.getState('bumble:is_open') == false) {
                    door_open_close(block, true)
                    if (!(block.hasTag("bumble:door_top"))) {
                        door_open_close(block.above(1), true)
                    }
                    if (block.hasTag("bumble:door_top")) {
                        door_open_close(block.below(1), true)
                    }
                }
            }

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

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

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

                case "bumble:template_door_bottom_flipped":

                    block.above(1).setPermutation(BlockPermutation.resolve("bumble:template_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 = "bumble:" + type + "_slab"
    if (block.typeId == req && item?.typeId == req) {
        block.dimension.playSound('use.wood', block.center())
        decrementstack(item, player)
        block.setPermutation(BlockPermutation.resolve("bumble:" + 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('bumble:is_open', istrue))
    if (!(block.hasTag('bumble:door_top')) && istrue == true) {
        block.dimension.playSound('open.wooden_door', block.center())
    }
    if (!(block.hasTag('bumble: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)
})
