import { Block, BlockPermutation, ItemStack, Player } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import { getGamemode } from "../../library/worldFuntions";

/**
 * Interfaz de bateria
 * @param {Player} player 
 * @param {Block} block 
 * @param {ItemStack} item 
 */
export const replaceCell = (player, block, item) => {
    const actionForm = new ActionFormData();

    actionForm.title("view.title.cell_charge");
    const charge = block.permutation.getState('nps_ec:charge');
    const chargeLost = (5 - charge);
    
    if (!chargeLost) return;
    actionForm.body("hud.descripton.cell_charge");
    if (chargeLost) {
        for (let i = 0; i < chargeLost; i++) {
            if (getGamemode(player) === 'survival' || getGamemode(player) === 'adventure') {
                let remainingCells = item.amount > i ? item.amount - i : 0;
                if (remainingCells > 0) {
                    actionForm.button({ translate: "view.button.charge_cell", with: [`${i + 1}`, i + 1 > 1 ? "s" : "" ] });
                }
            } else {
                actionForm.button({ translate: "view.button.charge_cell", with: [`${i + 1}`, i + 1 > 1 ? "s" : ""] });
            }
        }

        actionForm.show(player).then((data) => {
            if (data.canceled) return;
            const permutation = BlockPermutation.resolve('nps_ec:battery', { 'nps_ec:charge': (charge + data.selection + 1) })
            block.setPermutation(permutation);
            const unloadedCell = new ItemStack("nps_ec:battery_cell_unloaded", data.selection + 1)
            if (getGamemode(player) === 'survival' || getGamemode(player) === 'adventure') {
                if (item.amount - (data.selection + 1) != 0) {
                    player.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 nps_ec:battery_cell ${item.amount - (data.selection + 1)}`)
                } else {
                    player.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 air`)
                }
                if (player.getComponent("minecraft:inventory")?.container.emptySlotsCount) {
                    player.getComponent("minecraft:inventory")?.container.addItem(unloadedCell)
                } else {
                    player.dimension.runCommandAsync(`loot spawn ${player.location.x} ${player.location.y} ${player.location.z} loot "items/battery_cell_${data.selection + 1}"`)
                }
            }
        })
    }
}