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

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

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

      if (!lambdaSpawn.direction || !hasGrid) {
        return;
      }

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

      const lambda = new FunctionBox(grid.gridPosition, lambdaSpawn.code);
      const lambdaGrid = lambda.getComponent<Grid>(SystemNames.Grid)!;
      lambdaGrid.movingDirection = lambdaSpawn.direction;
      lambda.addComponent(lambdaGrid);
      game.addEntity(lambda);

      lambdaSpawn.direction = null;
      entity.addComponent(lambdaSpawn);
    });
  }
}
