import { GameMode, system, world } from "@minecraft/server";
import { sendAllMessage, sendPlayerMessage } from "../../config";
import { revivelist, setScore, lifesteal, envSteal, deadplayers, addScore, getScore, gameruleSwitcheroo } from "../../lifesteal";

// Core revive system
system.runInterval(() => {
    for (let player of world.getAllPlayers()) {
        let target = player.hasTag(`ls-revive`) ? player : undefined;
        if (!target) continue;
        if (!target.hasTag(`ls-dead`)) {
            target.removeTag(`ls-revive`);
            continue;
        }

        let revived: string[] = revivelist.has(player.name.toLowerCase()) ? revivelist.get(player.name.toLowerCase()).split(`.,`) : undefined;
        revivelist.delete(player.name.toLowerCase());
        deadplayers.delete(player.name.toLowerCase());

        const extrahearts = getScore(player, `ls-extra-hearts`) ?? 0;
        setScore(player, `ls-death`, +lifesteal.get(`reviveamount`) + extrahearts);
        if (getScore(player, `ls-extra-hearts`) > 0) sendPlayerMessage(player, `§bYou were given ${extrahearts} extra heart${extrahearts > 1 ? `s` : ``} because of your heart of life!`);

        if (player.getGameMode() === GameMode.spectator) player.setGameMode(GameMode.survival);
        target.removeTag(`ls-dead`);
        target.addEffect(`resistance`, 60, { amplifier: 255, showParticles: false });
        if (revived && revived[1]) {
            target.runCommandAsync(`title @s actionbar §bYou were revived by §f${revived[1]}§b!`);
            sendPlayerMessage(player, `§bYou were revived by §f${revived[1]}§b!`);
        }
        else {
            target.runCommandAsync(`title @s actionbar §bYou were revived!`);
            sendPlayerMessage(player, `§bYou were revived!`);
        }

        if (world.gameRules.showDeathMessages) {
            gameruleSwitcheroo(`showdeathmessages`, false);
        }
        if (!world.gameRules.doImmediateRespawn) {
            gameruleSwitcheroo(`doimmediaterespawn`, true);
        }

        player.addTag(`ls-message-debounce`);

        if (!player.getSpawnPoint()) {
            if (envSteal == true) {
                player.kill();
                system.run(() => {
                    addScore(player, `ls-death`, +lifesteal.get(`heartlose`));
                });
                return;
            }
            player.kill();
            return;
        }
        target.teleport(target.getSpawnPoint(), { dimension: target.getSpawnPoint().dimension });

        // To prevent the "you lost a heart" message
        player.removeTag(`ls-message-debounce`);
    }
}, 1);