import { ISimAction, SimLevel, SimMain, SimProjectile } from "../index.js";

export class SimActionMoveProjectiles implements ISimAction {
    public execute(simMain: SimMain) {
        const simLevel = simMain.currentLevel as SimLevel;
        const deadProjectiles: number[] = [];
        simLevel.simProjectiles.forEach((simProjectile: SimProjectile, idx: number) => {
            if (simProjectile.dead)
                deadProjectiles.push(idx);
        });

        for (const idx of deadProjectiles) {
            simLevel.simProjectiles.splice(idx, 1);
        }

        simLevel.simProjectiles.forEach((simProjectile: SimProjectile) => {
            const target = simLevel.simEnemies[simProjectile.targetEnemyIdx];
            if (!target || target.dead) {
                simProjectile.dead = true;
                return;
            }

            const pos1 = simProjectile.position;
            const pos2 = target.position;
            const dir = pos2.subtract(pos1);
            const len = dir.magnitude();
            let duration = simProjectile.speed / simMain.gdRoot.simulation.stepsPerSecond;
            if (len < duration) {
                duration = len;
                simProjectile.dead = true;
                target.suffer(simProjectile.gdEffect);
            }
            simProjectile.position = pos1.add(dir.normalized().multiplyScalar(duration));
        });
    }
}
