import { EEnemySize, GdRoot } from "../GameData/index.js";
import { SimEnemy } from "../Simulation/index.js";
import { Vector2 } from "../Util/index.js";

export class VisEnemy {
    private _positions: Vector2[];
    private _directions: Vector2[];
    private _image: HTMLCanvasElement;
    private _context: CanvasRenderingContext2D;
    private _simEnemy: SimEnemy;
    private _angle: number | null = null;
    private _gdRoot: GdRoot;

    constructor(gdRoot: GdRoot, simEnemy: SimEnemy, width: number, height: number) {
        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 get positions(): Vector2[] {
        return this._positions;
    }

    public get image(): HTMLCanvasElement {
        return this._image;
    }

    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._gdRoot.image("enemy-" + (this._simEnemy.index | 0) + ".svg"), -this._image.width / 2, -this._image.height / 2, this._image.width, this._image.height);
        ctx.restore();
    }
}
