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

const doubleTapTime = 5;
const dodgeCooldown = 40;
let playerData = {};

system.runInterval(() => {

    for (const player of world.getAllPlayers()) {
        const id = player.id;

        if (!playerData[id]) {
            playerData[id] = {
                lastMoveKey: null,
                lastMoveTime: 0,
                lastDodgeTick: -dodgeCooldown,
                isKeyPressed: false,
            };
        }

        const data = playerData[id];
        let now = system.currentTick;
        let velocity = player.getVelocity();
        let movementKey = getMovementDirection(velocity);

        if (movementKey) {
            if (!data.isKeyPressed) {
                if (movementKey === data.lastMoveKey && now - data.lastMoveTime <= doubleTapTime) {
                    //console.log(now - playerData[id].lastDodgeTick < dodgeCooldown, now - playerData[id].lastDodgeTick, dodgeCooldown);
                    if (now - data.lastDodgeTick >= dodgeCooldown && !player.hasTag("useSkill")) {
                        player.addTag("useSkill");

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

                        executeDodge(player, movementKey);
                        data.lastDodgeTick = now;
                    } else {
                        world.sendMessage(`${player.name}, il dodge è in cooldown!`);
                    }
                }
                data.lastMoveKey = movementKey;
                data.lastMoveTime = now;
            }
            data.isKeyPressed = true;
        } else {
            data.isKeyPressed = false;
        }
    }
}, 1);

function getMovementDirection(velocity) {

    if (Math.abs(velocity.x) > 0.1) {
        return velocity.x > 0 ? "D" : "A";
    }
    if (Math.abs(velocity.z) > 0.1) {
        return velocity.z > 0 ? "S" : "W";
    }
    return null;
}

function executeDodge(player, direction) {
    let speed = 0.5;
    let dodgeX = 0;
    let dodgeZ = 0;

    if (direction === "D") {
        dodgeX = speed;
        //player.playAnimation("animation.dodge_est");
    }
    else if (direction === "A") {
        dodgeX = -speed;
        //player.playAnimation("animation.dodge_west");
    }
    else if (direction === "W") {
        dodgeZ = -speed;
        //player.playAnimation("animation.dodge_north");
    }
    else if (direction === "S") {
        dodgeZ = speed;
        //player.playAnimation("animation.dodge_south");
    }
    player.playAnimation("animation.dodge_north");
    player.applyKnockback(dodgeX, dodgeZ, 2, 0.4);
    modifyStamina(player, 15, "remove");
    player.playSound("msft:ability:dash");
    player.removeTag("useSkill");
}