import { GdRoot } from "../../GameData/index.js";
import { Hex } from "../../Util/index.js";
import { ECellType, ISimCommand, SimEnemy, SimLevel, SimTower } from "../index.js";

export class SimCommandCreateTower implements ISimCommand {
    private _hex: Hex;
    private _simLevel: SimLevel;
    private _index: number;
    private _gdRoot: GdRoot;

    constructor(game: GdRoot, level: SimLevel, hex: Hex, index: number) {
        this._gdRoot = game;
        this._hex = hex;
        this._simLevel = level;
        this._index = index;
    }

    execute() {
        const level = this._simLevel;
        const cellIndex = level.getCellIndex(this._hex);
        const cell = level.simCells[cellIndex];
        const towerData = this._gdRoot.towers[this._index];

        if (cell.type != ECellType.Free) {
            return;
        }

        if (cell.simTower != null) {
            return;
        }

        level.simEnemies.forEach((enemy: SimEnemy) => {
            const hex = Hex.fromWorld(enemy.position);
            const enemyCellIndex = level.getCellIndex(hex);
            if (cellIndex == enemyCellIndex) {
                return;
            }
        });

        if (level.currency < towerData.cost) {
            return;
        }

        if (level.reservePaths(this._hex)) {
            level.currency -= towerData.cost;
            cell.simTower = new SimTower(this._gdRoot, level, this._index, this._hex);
            level.updatePaths();
        }
    }
}
