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


/**
 * Moving Enemy
 */
export class Enemy1 extends Tile {

    currentDirection: Direction = "down";   // direction, in which enemy moves currently

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

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

        // This makes scene.update call the update-method of this class each 1/60 s.
        // Beware: Don't forget to remove Listener when this object gets destroyed!
        this.scene.events.addListener('update', this.update, this);

    }


    /**
     * Store, after how many frames this objects moves again:
     */
    frameNumber: number = framesPerStep;

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

            let i = 0;
            let currentDirectionIndex = Directions.indexOf(this.currentDirection);

            /**
             * Look at all four directions relative to currentDirection in this order: 
             */
            let prios = [-1, 0, 1, 2];
            while (i < 4) {
                let newDirection = Directions[(currentDirectionIndex + prios[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();
    }


}