import * as mc from "@minecraft/server";
import * as utils from "../utils/index";
import { ignoreEntities } from "../shared/constants";
const expandDuration = 2 * 20;
const expandMin = 5;
const expandMax = 10;
const contractDuration = 1 * 20;
const contractMin = 0;
const contractMax = expandMax;
const swordDamage = 9;
export async function diamondAbility(player) {
    utils.mclog(`diamond`);
    player.runCommand(`playanimation @s animation.diamond_ability_swords.spin`);
    mc.world.playSound('beacon.power', player.location);
    // expand
    let startTime = mc.system.currentTick;
    let endDuration = mc.system.currentTick + expandDuration;
    await utils.waitForLoopEvent(5, () => {
        const distance = lerp(expandMin, expandMax, normalize(startTime, endDuration, mc.system.currentTick));
        player.dimension.getEntities({ location: player.location, maxDistance: distance, excludeTypes: ignoreEntities, excludeNames: [player.nameTag], excludeTags: ['friendlyFireOff'] }).forEach(victim => {
            victim.applyDamage(swordDamage, { damagingEntity: player.UnsafeEntity, cause: mc.EntityDamageCause.entityAttack });
        });
        return mc.system.currentTick >= endDuration;
    });
    // contract
    startTime = mc.system.currentTick;
    endDuration = mc.system.currentTick + contractDuration;
    await utils.waitForLoopEvent(5, () => {
        const distance = lerp(contractMax, contractMin, normalize(startTime, endDuration, mc.system.currentTick));
        player.dimension.getEntities({ location: player.location, maxDistance: distance, excludeTypes: ignoreEntities, excludeNames: [player.nameTag], excludeTags: ['friendlyFireOff'] }).forEach(victim => {
            victim.applyDamage(swordDamage, { damagingEntity: player.UnsafeEntity, cause: mc.EntityDamageCause.entityAttack });
        });
        return mc.system.currentTick >= endDuration;
    });
    // launch
    for (let angle = 0; angle < 360; angle += 90) {
        const direction = new utils.Vector3({ x: 0, y: 0, z: 1 }).rotateByAngle(angle);
        const origin = new utils.Vector3(player.getHeadLocation()).add(direction.multiply(1.5));
        const projectile = player.dimension.spawnEntity('ldz:diamond_ability_projectile_spawner', origin);
        projectile.runCommand(`tp @s ~ ~ ~ ${angle} 0`);
        mc.world.playSound('ability.diamond.swing', origin);
    }
}
function lerp(a, b, alpha) {
    return a + alpha * (b - a);
}
function normalize(min, max, value) {
    return utils.clamp((value - min) / (max - min), 0, 1);
}
