import { Block, Dimension, Player } from "@minecraft/server";
import { checkAnyNeighborHasTag, checkTopOrBottomNeighborHasTag } from "../../library/blockManager";
import { addDamageItem, decrementItemStack } from "../../library/itemManager";

/**
 * Evento del componente analyzerActionComponent
 * @param {{player: Player, block: Block, dimension: Dimension}} event 
 */
export const copperMobSpawnerActionEvent = ({ player, block, dimension }) => {
    const inventory = player.getComponent('minecraft:inventory');
    if (!inventory) return;
    const item = inventory.container.getItem(player.selectedSlotIndex);
    if (!item) return;
    let permutation = block.permutation;

    const state = permutation.getState('nps_ec:state');

    const variantMappings = {
        'minecraft:bone': 'skeleton',
        'minecraft:rotten_flesh': 'zombie',
        'minecraft:beef': 'cow',
        'minecraft:mutton': 'sheep',
        'minecraft:porkchop': 'pig',
        'minecraft:chicken': 'chicken',
        'minecraft:gunpowder': 'creeper'
    }

    const itemTypeId = item.typeId;
    if(state >= 0 && state <= 3) {
        if (variantMappings[itemTypeId]) {
            if (!checkAnyNeighborHasTag(block, 'power:on')) return;
            permutation = permutation.withState('nps_ec:variants', variantMappings[itemTypeId]);
            decrementItemStack(item, player);
        } else if(item.hasTag('minecraft:is_axe') &&  state != 0) {
            addDamageItem(item, player, 400);
            dimension.runCommand(`playsound copper.wax.off @a ${block.x} ${block.y} ${block.z}`);
            permutation = permutation.withState('nps_ec:state', 0)
        }
    } else {
        if (variantMappings[itemTypeId]) {
            if (!checkAnyNeighborHasTag(block, 'power:on')) return;
            permutation = permutation.withState('nps_ec:variants', variantMappings[itemTypeId]);
            decrementItemStack(item, player);
        } else if(item.hasTag('minecraft:is_axe')) {
            if(state == 15 && permutation.getState('nps_ec:destroy') > 0) {
                permutation = permutation.withState('nps_ec:destroy', 0);
            } else {
                const currentState = permutation.getState('nps_ec:state')
                addDamageItem(item, player, 400);
                dimension.runCommand(`playsound copper.wax.off @a ${block.x} ${block.y} ${block.z}`);
                permutation = permutation.withState('nps_ec:state', currentState - 4)
            }
        }
    }

    block.setPermutation(permutation);
};