import { world, Player, EntityInventoryComponent, ItemStack, system } from '@minecraft/server';
import { Command } from '../handler';
import { sendPlayerMessage, config, sendAllMessage } from '../../config';
import { addScore, gameruleSwitcheroo, getScore } from '../../lifesteal';

export function withdrawHelp(player: Player) {
    sendPlayerMessage(player, `§e§lLifesteal Help Page -- Withdraw§r§6
> Withdraw a certain amount of hearts into your inventory

> Usage: ${config.prefix}withdraw <amount>

> Examples: [
${config.prefix}withdraw 3
${config.prefix}withdraw 6
]`);
}

new Command({
    name: `withdraw`,
    code({ player, args }) {
        let amount = +args[0];
        if (!args[0]) return withdrawHelp(player);
        if (isNaN(amount)) return sendPlayerMessage(player, `§8[§cX§8] §cFailed to withdraw, §l${args[0]}§r§c is Not a Number`);
        if (amount > getScore(player, `ls-death`) || amount == getScore(player, `ls-death`)) return sendPlayerMessage(player, `§8[§cX§8] §cYou cannot withdraw more hearts than you currently have! (${getScore(player, `ls-death`)})`);
        if (amount < 1) return sendPlayerMessage(player, `§8[§cX§8] §cYou cannot withdraw less than 1 heart!`);

        addScore(player, `ls-death`, -amount);
        let inventory = (player.getComponent(`inventory`) as EntityInventoryComponent)[`container`];
        let inventorySize = inventory.size;
        for (let i = 0; i < inventorySize; i++) {
            let item = inventory.getItem(i);
            if (!item || item.typeId !== `lifesteal:heart`) continue;
            inventory.setItem(i, new ItemStack(item.typeId, item.amount));
        }

        if (world.gameRules.sendCommandFeedback) {
            gameruleSwitcheroo(`sendCommandFeedback`, false);
        }
        player.runCommandAsync(`give @s lifesteal:heart ${amount}`);
        sendPlayerMessage(player, `§8[§a/§8] §aWithdrew §f${amount}§a hearts`);
        player.playSound(`mob.chicken.plop`, { pitch: 4 });
    }
});