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

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

    const capsuleState = permutation.getState('nps_ec:capsule');
    const actionState = permutation.getState('nps_ec:action');

    if (!actionState && !capsuleState && item.typeId === 'nps_ec:digital_dna_capsule') {
        permutation = permutation.withState('nps_ec:capsule', true);
        decrementItemStack(item, player);
    } else if (!actionState && capsuleState) {
        const itemTypeId = item.typeId;
        const variantMappings = {
            'minecraft:bone': 'skeleton',
            'minecraft:rotten_flesh': 'zombie',
            'minecraft:beef': 'cow',
            'minecraft:mutton': 'sheep',
            'nps_ec:digital_dna_cat_damage': 'cat',
            'nps_ec:digital_dna_wolf_damage': 'wolf',
            'minecraft:totem_of_undying': 'iron_golem'
        };

        if (variantMappings[itemTypeId]) {
            permutation = permutation.withState('nps_ec:action', true)
                                        .withState('nps_ec:center', true)
                                        .withState('nps_ec:variants', variantMappings[itemTypeId]);
            decrementItemStack(item, player);
        }
    }

    block.setPermutation(permutation);
};