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

export function reviveHelp(player: Player) {
    sendPlayerMessage(player, `§e§lLifesteal Help Page -- Revive§r§6
> Revive a player if they are a ghost, requires a heart of life in hand to work

> Usage: ${config.prefix}revive <player>

> Examples: [
${config.prefix}revive ${player.name}
${config.prefix}revive TestSubject8987
]`);
}

new Command({
    name: `revive`,
    code({ player, args }) {
        let inv = player.getComponent(`inventory`) as EntityInventoryComponent;
        let item = inv.container.getItem(player.selectedSlot);
        if (!item || item.typeId != `lifesteal:beacon_of_life`) return sendPlayerMessage(player, `§8[§cX§8] §cYou must have a beacon of life in your hand to revive a player!`);

        if (!args[0]) return reviveHelp(player);
        let target: string;
        for (let x of deadplayers.keys()) {
            if (x.toLowerCase() == args.join(` `).toLowerCase()) {
                target = x;
                break;
            }
        }
        if (!target) {
            for (let players of world.getAllPlayers()) {
                if (players.name.toLowerCase() == args.join(` `).toLowerCase()) return sendPlayerMessage(player, `§8[§cX§8] §cThat player is not a ghost!`);
            }
            return sendPlayerMessage(player, `§8[§cX§8] §cFailed to find player, the player must be a ghost`);
        }
        revivelist.set(`${target.toLowerCase()}`, `${target.toLowerCase()}.,${player.name}`);
        for (let x of deadplayers.keys()) {
            if (x.toLowerCase() == args.join(` `).toLowerCase()) {
                deadplayers.delete(x);
                break;
            }
        }

        player.runCommandAsync(`clear @s lifesteal:beacon_of_life 0 1`);
        sendAllMessage(`§b${player.name} has revived ${target}`);

        player.runCommandAsync(`playsound heart_of_life_sound @a`);
    }
}); 