import { ItemStack, system, BlockPermutation } from "@minecraft/server";
import { liquidConfigs, liquidsData, liquidLevel } from "./data";


system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:liquid_barrel", {
        onPlayerInteract: e => {
            const { player, block, dimension } = e;

            const liquidLevel = block.permutation.getState("r:fill");
            const liquidType = block.permutation.getState("r:type");
            const equipment = player.getComponent('equippable');
            const selectedItem = equipment.getEquipment('Mainhand');

            if ( !selectedItem ) return;

            const extractConfigs = {
                'minecraft:glass_bottle': { sound: ['cauldron.takepotion', 'bottle.fill'], item: liquidsData[liquidType].items[0], levelCheck: level => level > 0, levelChange: -1 },
                'minecraft:bucket':       { sound: ['cauldron.takepotion'], item: liquidsData[liquidType].items[1], levelCheck: level => level === 3, levelChange: -3 }
            };

            let item = undefined;

            if (liquidConfigs[selectedItem.typeId]){
                
                const config = liquidConfigs[selectedItem.typeId];
                if ((liquidLevel != 3 && liquidType == 0) || (liquidLevel != 3 && liquidType == config.type) || liquidLevel == 0) {
                    block.setPermutation(block.permutation.withState("r:type", config.type));
                    const newLevel = config.fullFill ? 3 : liquidLevel + config.fillAmount;
                    block.setPermutation(block.permutation.withState("r:fill", newLevel));

                    config.sounds.forEach(sound => {
                        dimension.runCommand(`playsound ${sound} @a ${block.x} ${block.y} ${block.z}`);
                    });

                    if (player.getGameMode() != "Creative") {
                        if (selectedItem.amount === 1) {
                            item = new ItemStack(config.replace, 1);
                        } else {
                            selectedItem.amount -= 1;
                            equipment.setEquipment('Mainhand', selectedItem);
                            player.getComponent("inventory").container.addItem(new ItemStack(config.replace, 1));
                        }
                    }
                }
            } else if (extractConfigs[selectedItem.typeId]) {
                const config = extractConfigs[selectedItem.typeId];

                if (config.levelCheck(liquidLevel)) {
                    block.setPermutation(block.permutation.withState("r:fill", liquidLevel + config.levelChange));
                    if (liquidLevel + config.levelChange <= 0) {
                        block.setPermutation(block.permutation.withState("r:type", 0));
                    }

                    config.sound.forEach(sound => {
                        dimension.runCommand(`playsound ${sound} @a ${block.x} ${block.y} ${block.z}`);
                    });

                    if (player.getGameMode() != "Creative") {
                        if (selectedItem.amount === 1) {
                            item = new ItemStack(config.item, 1);
                        } else {
                            selectedItem.amount -= 1;
                            equipment.setEquipment('Mainhand', selectedItem);
                            player.getComponent("inventory").container.addItem(new ItemStack(config.item, 1));
                        }
                    }
                }
            }
            if (item) equipment.setEquipment('Mainhand', item);
            
            
        },
        onPlayerBreak: e => {
            const block = e.block;
            const dimension = e.dimension;
            const blockPermutation = e.brokenBlockPermutation
            const liquidBarrel = new ItemStack(blockPermutation.type.id,1)
            const fillState = blockPermutation.getState("r:fill")
            const typeState = blockPermutation.getState("r:type")
            if (fillState != 0){
                liquidBarrel.setLore(["§r" + liquidsData[typeState].color + liquidsData[typeState].type, "§r§7" + liquidLevel[fillState].mL + "/1500"])
            }
            dimension.spawnItem(liquidBarrel,block.center())
        },
        beforeOnPlayerPlace: e => {
            const player = e.player;
            const permutationToPlace = e.permutationToPlace;
            const equipment = player.getComponent('equippable');
            const selectedItem = equipment.getEquipment('Mainhand');

            const itemLore = selectedItem.getLore()
            if (!itemLore[0]) return;

            let fillState = itemLore[1].slice(4).split("/")[0]

            if (fillState == "1500") fillState = 3
            else if (fillState == "1000") fillState = 2
            else fillState = 1

            for (const key in liquidsData) {
                if (liquidsData[key].type == itemLore[0].slice(4)) {
                    e.permutationToPlace = BlockPermutation.resolve(permutationToPlace.type.id,{"r:type": Number(key), "r:fill": fillState})
                }
            }
        }
    });
});
