import { EntityComponentTypes, system, world } from "@minecraft/server";
import { modifyStamina } from "../stamina";

const slideDuration = 8;
const slideCooldown = 100;
let playerData = {};

let sprintingPlayers = new Set();

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        let playerId = player.id;

        if (!playerData[playerId]) {
            playerData[playerId] = {
                lastSlideTick: -slideCooldown
            }
        }

        if (player.isSprinting) {
            sprintingPlayers.add(playerId);
        } else {
            let run = system.runTimeout(() => {
                if (sprintingPlayers.has(playerId)) {
                    if (player.isSprinting) {
                        system.clearRun(run);
                    } else {
                        sprintingPlayers.delete(playerId);
                    }
                }
            }, 1);
        }

        if (player.isSneaking && sprintingPlayers.has(playerId)) {
            if (!player.isOnGround) continue;
            sprintingPlayers.delete(playerId);
            let slideTicks = 0;
            let now = system.currentTick;
            let scaleComponent = player.getComponent(EntityComponentTypes.Scale);
            if (now - playerData[playerId].lastSlideTick < slideCooldown) {
                player.sendMessage("Slide in cooldown");
                continue;
            }

            if (player.hasTag("useSkill")) continue;
            
            if (player.hasTag("isExahust")) {
                player.playSound("msft:ambient:no-mana");
                continue;
            }

            let slideInterval = system.runInterval(() => {
                if (slideTicks >= slideDuration || !player.isSneaking || player.hasTag("isExahust")) {
                    system.clearRun(slideInterval);
                    sprintingPlayers.delete(playerId);
                    scaleComponent.value = 1;
                    player.playAnimation("animation.slide_end");
                } else {
                    slideTicks === 0 ? player.playAnimation("animation.slide_start") : player.playAnimation("animation.slide_loop");
                    player.addTag("useSkill");
                    scaleComponent.value = 0.65;
                    player.applyKnockback(player.getViewDirection().x, player.getViewDirection().z, 2, 0);
                    player.removeTag("useSkill");
                    slideTicks++;
                }
            }, 0.5);

            player.playSound("msft:ability:slide");
            modifyStamina(player, 10, "remove");
            sprintingPlayers.delete(playerId);
            playerData[playerId].lastSlideTick = now;
            scaleComponent.value = 1;
            player.removeTag("useSkill");

        }
    };
}, 1);