import { Level } from "./Level.js";
import { MainScene } from "./MainScene.js";
import { Tile } from "./Tile.js";
import { Direction, DirectionMap, Directions, framesPerStep, stepDurationInMs } from "./Globals.js";

/**
 * Comments: See Enemy1
 */

export class Enemy2 extends Tile {

    currentDirection: Direction = "down";

    constructor(private mainScene: MainScene, public column: number, public row: number, public level: Level) {

        super(mainScene, column, row, "enemy2", level);

        this.scene.events.addListener('update', this.update, this);

    }


    frameNumber: number = framesPerStep;

    update() {
        this.frameNumber--;
        if (this.frameNumber <= 0) {
            this.frameNumber = framesPerStep;

            let i = 0;
            let directionIndex = Directions.indexOf(this.currentDirection);
            let deltas = [0, -1, 1, 2];
            while (i < 4) {
                let newDirection = Directions[(directionIndex + deltas[i] + 4) % 4];
                let tile = this.getTile(newDirection);
                if (tile == null) {
                    let directionMapEntry = DirectionMap[newDirection];
                    this.goTo(this.column + directionMapEntry.dx, this.row + directionMapEntry.dy);
                    this.currentDirection = newDirection;
                    break;
                } else if (tile.kind == "player") {
                    this.mainScene.gameOver();
                    break;
                }
                i++;
            }

        }
    }

    getTile(direction: Direction): Tile {
        let directionMapEntry = DirectionMap[direction];
        return this.level.tiles[this.column + directionMapEntry.dx][this.row + directionMapEntry.dy];
    }

    destroyTile(tile: Tile) {
        this.scene.tweens.add({
            targets: tile,
            alpha: 0,
            duration: stepDurationInMs,
            onComplete: () => {
                tile.destroy();
            }
        })
    }

    destroy(): void {
        this.scene.events.removeListener('update', this.update);
        super.destroy();
    }


}