import { world, Player, system, EquipmentSlot, Vector, ItemStack } from "@minecraft/server";
import { ActionFormData, FormCancelationReason, ModalFormData } from "@minecraft/server-ui";
import { sendPlayerMessage, sendAllMessage, config } from "../../../config";
import { deadplayers, revivelist } from "../../../lifesteal";
import { Command } from "../../handler";

export function reviveGuiForm(player: Player) {
    let options: string[] = Array.from(deadplayers.keys());

    if (!options.length) {
        const errorGui = new ModalFormData()
            .title(`Revive GUI`)
            .textField(`Search for a player`, `e.g GamerDos7511`)
            .dropdown(`Choose a player to revive`, [`No dead players!`]);
        errorGui.show(player).then(result => {
            if (result.canceled && result.cancelationReason == `UserBusy`) return reviveGuiForm(player);
            if (result.canceled && result.cancelationReason == `UserClosed` || !(result.formValues[0] as any).length) return;
            sendPlayerMessage(player, `§cThere are no dead players!`);
        });
        return;
    }

    const reviveGUI = new ModalFormData()
        .title(`Revive GUI`)
        .textField(`Search for a player`, `e.g GamerDos7511`)
        .dropdown(`Choose a player to revive`, options);
    reviveGUI.show(player).then(result => {
        if (result.canceled && result.cancelationReason == `UserBusy`) return reviveGuiForm(player);
        else if (result.canceled) return;
        if (result.formValues[0]) {
            let search: string[] = [];
            for (let x of options) {
                if (x.includes(<any>result.formValues[0])) search.push(x);
            }
            if (!search.length) {
                const reviveGuiSearchUnsuccessful = new ModalFormData()
                    .title(`Revive GUI - Search Error`)
                    .dropdown(`Choose a player to revive`, [`No players found!`]);
                reviveGuiSearchUnsuccessful.show(player).then(() => {
                    reviveGuiForm(player);
                });
                return;
            }
            options = search;
            reviveGuiForm(player);
            return;
        }

        let formValues = result.formValues;
        let target = options[<any>formValues[1]];

        player.runCommand(`clear @s lifesteal:beacon_of_life 0 1`);
        revivelist.set(`${target.toLowerCase()}`, `${target.toLowerCase()}.,${player.name}`);
        deadplayers.delete(target);
        sendAllMessage(`§b${player.name} has revived ${target}`);

        for (const player of world.getAllPlayers()) {
            player.playSound(`heart_of_life_sound`);
        }
    });
}


world.afterEvents.itemUse.subscribe(data => {
    if (data.itemStack.typeId == `lifesteal:beacon_of_life`) {
        let player = data.source as Player;

        reviveGuiForm(player);
    }
});