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

/**
 * Evento del componente furnaceEnergyOffComponent
 * @param {{block: Block, dimension: Dimension}} event 
 */
export const furnaceEnergyOffEvent = ({ block, dimension }) => {
    try {
        if (!block) return;
        if (block.typeId == 'minecraft:air') return


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

        if (power && state == 0) {
            const permutation = block.permutation.withState('nps_ec:power', 0);
            block.setPermutation(permutation);
        } else {
            const permutation = block.permutation.withState('nps_ec:state', block.permutation.getState('nps_ec:state') - 1);
            block.setPermutation(permutation);
        }
    } catch {  }
}


/**
 * Evento del componente furnaceEnergyOnComponent
 * @param {{block: Block, dimension: Dimension}} event 
 */
export const furnaceEnergyOnEvent = ({ block, dimension }) => {
    try {
        if (!block) return;
        if (block.typeId == 'minecraft:air') return


        const power = block.permutation.getState('nps_ec:power');

        if (!power) {
            const { blockNeighborUp } = blockNeighbors(block);
            if (blockNeighborUp.typeId == 'minecraft:hopper') {
                const inventory = blockNeighborUp.getComponent('minecraft:inventory');

                const toggleBit = blockNeighborUp.permutation.getState('toggle_bit');

                if (toggleBit) return;

                for (let i = 0; i < inventory.container.size; i++) {
                    const item = inventory.container.getItem(i);
                    if (item && item.typeId == 'minecraft:coal_block') {
                        let permutation = block.permutation.withState('nps_ec:power', 1);
                        permutation = permutation.withState('nps_ec:state', 4);
                        block.setPermutation(permutation);
                        inventory.container.setItem(i, decrementItemStackObject(item, 1));
                        break;
                    }
                }
            }
        }
    } catch {  }
}