import { SimMain } from "../SimMain";
import { SimProjectile } from "../SimProjectile";
import { ISimAction } from "./ISimAction";

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

        for (const idx of deadProjectiles) {
            level.projectiles.splice(idx, 1);
        }

        level.projectiles.forEach((simProjectile: SimProjectile) => {
            const target = level.enemies[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.projectileEffect.speed / simMain.gdRoot.simulation.stepsPerSecond;
            if (len < duration) {
                duration = len;
                simProjectile.dead = true;
                target.suffer(level, simProjectile.projectileEffect);
            }
            simProjectile.prevPosition = simProjectile.position;
            simProjectile.position = pos1.add(dir.normalized().multiplyScalar(duration));
        });
    }
}
