import { Block, Dimension, Player } from "@minecraft/server"
import { getGamemode } from "../../library/worldFuntions";
import { blockNeighbors, checkAnyNeighborHasBlockType, checkAnyNeighborHasTag } from "../../library/blockManager";

/**
 * Evento Tick del componente digitalTntComponent
 * @param {{block: Block, dimension: Dimension}} event 
 */
export const digitalTntTickeEvent = ({ block, dimension }) => {
    try {
        const {
            blockNeighborDown, blockNeighborUp,
            blockNeighborEast, blockNeighborWest,
            blockNeighborNorth, blockNeighborSouth
        } = blockNeighbors(block);
    
        // Verificar que todos los vecinos existan
        if (!blockNeighborUp || !blockNeighborDown ||
            !blockNeighborEast || !blockNeighborWest ||
            !blockNeighborNorth || !blockNeighborSouth) return;
    
        if(checkAnyNeighborHasTag(block, 'power:on')) {
            dimension.runCommand(`setblock ${block.x} ${block.y} ${block.z} air replace`)
            dimension.runCommand(`summon nps_ec:digital_tnt ${block.x} ${block.y} ${block.z}`)
        }
    } catch { }
}

/**
 * Evento OnIteract del componente digitalTntComponent
 * @param {{player: Player, block: Block, dimension: Dimension}} event 
 */
export const digitalTntOnInteractEvent = ({ 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:plasma_lighter') return;

    if (getGamemode(player) === 'survival' || getGamemode(player) === 'adventure') {
        const damage = item.getComponent('minecraft:durability').damage + 2;

        player.runCommand(`replaceitem entity @s slot.weapon.mainhand 0 nps_ec:plasma_lighter 1 ${damage}`)
    }

    dimension.runCommand(`setblock ${block.x} ${block.y} ${block.z} air replace`)
    dimension.runCommand(`summon nps_ec:digital_tnt ${block.x} ${block.y} ${block.z}`)
}