import { Block, Dimension } from "@minecraft/server";
import { blockNeighbors, checkAnyNeighborHasTag, findNeighborWithTagAndCoordinates } from "../../library/blockManager";
import { replaceCell } from "../../views/blocks/batteryView";

/**
 * Evento Tick del componente buttonReloadComponent
 * @param {{block: Block, dimension: Dimension}} event 
 */
export const batteryTickEvent = ({ block, dimension }) => {
    try {
        const {
            blockNeighborUp, blockNeighborDown,
            blockNeighborEast, blockNeighborWest,
            blockNeighborNorth, blockNeighborSouth
        } = blockNeighbors(block);

        if(!blockNeighborUp || !blockNeighborDown ||
            !blockNeighborEast || !blockNeighborWest ||
            !blockNeighborNorth || !blockNeighborSouth) return;

        if(!block) return;
        let permutation = block.permutation;
        const chargeState = permutation.getState('nps_ec:charge');

        const hasPurePowerNeighbor = checkAnyNeighborHasTag(block, 'power:pure');

        if (!hasPurePowerNeighbor && chargeState !== 0) {
            // Randomize with weights: 30% chance to trigger charge down update, 70% chance to do nothing
            if (Math.random() < 0.3) {
                permutation = permutation.withState('nps_ec:charge', chargeState - 1);
            }
        } else if (hasPurePowerNeighbor && chargeState !== 5) {
            // Randomize with weights: 40% chance to trigger charge up update, 60% chance to do nothing
            if (Math.random() < 0.4) {
                permutation = permutation.withState('nps_ec:charge', chargeState + 1);
            }
        }

        block.setPermutation(permutation);
    } catch { }
}

/**
 * Evento OnIteract del componente clockPanelComponent
 * @param {{player: Player, block: Block, dimension: Dimension}} event 
 */
export const batteryInteractEvent = ({ player, block, dimension }) => {
    if (player.getComponent('minecraft:inventory') == undefined) return;
    const item = player.getComponent('minecraft:inventory').container.getItem(player.selectedSlotIndex);
    if(!item) return;
    if(item.typeId !== 'nps_ec:battery_cell') return;
    replaceCell(player, block, item);
}