import { AssetPreloaderService } from "../../../assetPreloaderService";
import { EEnemySize } from "../data/EEnemySize";
import { GdRoot } from "../data/GdRoot";
import { SimEnemy } from "../sim/SimEnemy";
import { Vector2 } from "../util/Vector2";

export class VisEnemy {
    positions: Vector2[];
    directions: Vector2[];
    image: HTMLCanvasElement;
    context: CanvasRenderingContext2D;
    private simEnemy: SimEnemy;
    private angle: number | null = null;
    private gdRoot: GdRoot;
    assets: AssetPreloaderService;

    constructor(gdRoot: GdRoot, assets: AssetPreloaderService, simEnemy: SimEnemy, width: number, height: number) {
        this.assets = assets;
        this.gdRoot = gdRoot;
        this.simEnemy = simEnemy;
        this.image = document.createElement("canvas");
        this.image.width = width;
        this.image.height = height;
        this.context = this.image.getContext("2d")!;
        this.positions = [simEnemy.position, simEnemy.position];
        this.directions = [simEnemy.direction, simEnemy.direction];
    }

    public advanceStep() {
        const prevPos = this.positions[1];
        const prevDir = this.directions[1];
        this.positions = [prevPos, this.simEnemy.position];
        this.directions = [prevDir, this.simEnemy.direction];
    }

    public update(t: number) {
        const directions = this.directions;
        const dir = Vector2.lerp(directions[0], directions[1], t);
        const angle = Math.atan2(dir.x, -dir.y) - Math.PI / 2;
        if (this.angle == angle) {
            return;
        }
        this.angle = angle;
        const ctx = this.context;
        ctx.clearRect(0, 0, this.image.width, this.image.height);
        ctx.save();
        ctx.translate(this.image.width / 2, this.image.height / 2);
        ctx.rotate(angle);
        switch (this.simEnemy.size) {
            case EEnemySize.Tiny:
                ctx.scale(0.75, 0.75);
                break;
            case EEnemySize.Huge:
                ctx.scale(2, 2);
                break;
        }
        ctx.drawImage(this.assets.getImage("images/enemy-" + (this.simEnemy.index | 0) + ".svg"), -this.image.width / 2, -this.image.height / 2, this.image.width, this.image.height);
        ctx.restore();
    }
}
