import {world, ItemStack, BlockTypes} from '@minecraft/server';

world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockComponentRegistry.registerCustomComponent('custom:on_interact', {
        onPlayerInteract(event) {
            const {player, block, dimension, face} = event;
            
            const equipment = player.getComponent('equippable');

            const selectedItem = equipment.getEquipment('Mainhand');

            if (block.hasTag("state_lockable") && selectedItem?.typeId === "custom:tool") {
                let currentblockPermutation = Boolean(block.permutation.getState("custom:state_lock"))
                block.setPermutation(block.permutation.withState('custom:state_lock', !currentblockPermutation));
                player.onScreenDisplay.setActionBar(`§g(Block Lock Status: §e${block.permutation.getState("custom:state_lock")})`)
                player.playSound('random.click');
            }

            //Check if block has states by its block tag, and if the player is holding the tool to change the block's permutation, there is also a option to lock the state if needed
            if (block.hasTag("block_state") && selectedItem?.typeId === "custom:tool" && !block.permutation.getState("custom:state_lock")) {
                let currentblockPermutation = Number(block.permutation.getState("custom:alt_state"))
                let newBlockPermutation = currentblockPermutation+1
                block.setPermutation(block.permutation.withState('custom:alt_state', newBlockPermutation));
                player.onScreenDisplay.setActionBar(`§g(Block Alt Status: §e${block.permutation.getState("custom:alt_state")})`)
                player.playSound('use.chain');
            }
            // Check if the selected item is a block
            if (selectedItem && BlockTypes.get(selectedItem.typeId)) {

                // Acts like a blacklist for blocks.
                const notAllowBlockReplacementArray = [
                    'minecraft:air',
                    'minecraft:vine',
                    'minecrraft:glow_lichen',
                    'minecraft:short_grass',
                    'minecraft:tall_grass',
                    'minecraft:sea_grass',
                    'minecraft:fern',
                    'minecraft:large_fern',
                    'minecraft:waterlily'
                ]

                //Blocks that can be replaced.
                const allowBlockReplacementArray = [
                    'minecraft:air',
                    'minecraft:vine',
                    'minecrraft:glow_lichen',
                    'minecraft:short_grass',
                    'minecraft:tall_grass',
                    'minecraft:water',
                    'minecraft:sea_grass',
                    'minecraft:fern',
                    'minecraft:large_fern',
                    'minecraft:waterlily'
                ]
                
                //blocks that can't be placed on the block
                const blacklistedBlocksArray = [
                    'minecraft:barrier' // placeholder you can add blocks you want to blacklist.
                ]

                const directionMethods = {
                    Up: 'above',
                    Down: 'below',
                    North: 'north',
                    East: 'east',
                    South: 'south',
                    West: 'west',
                };

                const getAdjacentBlock = (direction) => block[directionMethods[direction]]();
                
                let passedChecks = false;
                let plrAlreadyWarned = false;
                if (blacklistedBlocksArray.includes(selectedItem.typeId)) {
                    const SoundOptions = {
                        pitch: 0.5,
                        volume: 1.0,
                        };
                    player.onScreenDisplay.setActionBar(`§7(You can't use that here!)`)
                    player.playSound('mob.villager.no', SoundOptions)
                    plrAlreadyWarned = true
                }

                // Ensure selectedItem.typeId is not blacklisted
                if (!notAllowBlockReplacementArray.includes(selectedItem.typeId) && !plrAlreadyWarned) {
                    // Calculate the position based on the face direction
                    if (directionMethods[face]) {
                        const setBlock = getAdjacentBlock(face);
                        
                        if (allowBlockReplacementArray.includes(setBlock.typeId)) {
                            setBlock?.setType(selectedItem.typeId);
                            passedChecks = true;
                        } else {
                            player.onScreenDisplay.setActionBar(`§7(This action is currently blocked!)`)
                            player.playSound('mob.villager.no')
                            plrAlreadyWarned = true
                        }
                    }
                } else if (notAllowBlockReplacementArray.includes(selectedItem.typeId)) {
                    player.onScreenDisplay.setActionBar(`§7(You can't use this block here!)`)
                    player.playSound('mob.villager.no')
                    plrAlreadyWarned = true
                }
                // Reduce item count if not in creative mode
                if (player.getGameMode() !== "creative" && passedChecks) {
                    if (selectedItem.amount > 1) {
                        selectedItem.amount -= 1;
                        equipment.setEquipment('Mainhand', selectedItem);
                    } else {
                        equipment.setEquipment('Mainhand', undefined); // Clear the slot if only 1 item left
                    }
                }
            }
        }
    });
});