import { Hex } from "../../util/Hex";
import { ECellType } from "../ECellType";
import { SimEnemy } from "../SimEnemy";
import { SimMain } from "../SimMain";
import { SimTower } from "../SimTower";
import { SimCommand } from "./SimCommand";

export class SimCommandCreateTower extends SimCommand {
    hex: Hex;
    index: number;

    constructor(hex: Hex, index: number) {
        super();
        this.hex = hex;
        this.index = index;
    }

    public execute(simMain: SimMain) {
        const level = simMain.currentLevel;
        if (!level) {
            return;
        }

        const cellIndex = level.getCellIndex(this.hex);
        const cell = level.cells[cellIndex];
        const towerData = simMain.gdRoot.towers[this.index];

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

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

        level.enemies.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(simMain.gdRoot, this.hex)) {
            level.currency -= towerData.cost;
            cell.tower = new SimTower(this.index, Hex.toWorld(this.hex));
            level.updatePaths(simMain.gdRoot);
        }
    }
}
