import { System, SystemNames } from ".";
import { Game } from "..";
import { ComponentNames, Grid, GridSpawn } from "../components";
import { Direction } from "../interfaces";

export class GridSpawner extends System {
  constructor() {
    super(SystemNames.GridSpawner);
  }

  public update(_dt: number, game: Game) {
    game.forEachEntityWithComponent(ComponentNames.GridSpawn, (entity) => {
      const spawn = entity.getComponent<GridSpawn>(ComponentNames.GridSpawn)!;
      const hasGrid = entity.hasComponent(SystemNames.Grid);

      if (spawn.direction === Direction.NONE || !hasGrid) {
        return;
      }

      const grid = entity.getComponent<Grid>(SystemNames.Grid)!;

      const direction = spawn.direction;
      const spawned = spawn.spawner();
      if (!spawned) {
        return;
      }
      spawn.direction = Direction.NONE;
      entity.addComponent(spawn);

      const spawnedGrid = spawned.getComponent<Grid>(SystemNames.Grid)!;
      spawnedGrid.gridPosition = grid.gridPosition;
      spawnedGrid.movingDirection = direction;
      spawned.addComponent(spawnedGrid);

      game.addEntity(spawned);
      entity.addComponent(spawned);
    });
  }
}
