import { LEVELS, Level, LevelNames } from ".";
import { Game } from "..";
import { Grass, Player, Portal } from "../entities";
import { Grid, Level as LevelSystem, SystemNames } from "../systems";
import { normalRandom } from "../utils";

export class LevelSelection extends Level {
  public static RADIUS = 5;

  constructor() {
    super(LevelNames.LevelSelection);
  }

  public init(game: Game): void {
    const gridSystem = game.getSystem<Grid>(SystemNames.Grid);
    const center = gridSystem.getCenterGrid();
    const dimensions = gridSystem.getGridDimensions();

    const levelSystem = game.getSystem<LevelSystem>(SystemNames.Level);
    const unlocked = levelSystem.getUnlockedLevels();

    const renderableLevels = LEVELS.filter(
      ({ name }) => name !== LevelNames.LevelSelection,
    );
    const radiansPerLevel = (2 * Math.PI) / renderableLevels.length;
    renderableLevels
      .filter(({ name }) => unlocked.has(name))
      .map((level, i) => {
        const radians = i * radiansPerLevel;
        const coords = {
          x: Math.floor(Math.cos(radians) * LevelSelection.RADIUS + center.x),
          y: Math.floor(Math.sin(radians) * LevelSelection.RADIUS + center.y),
        };
        return new Portal(level.name, coords);
      })
      .forEach((e) => game.addEntity(e));

    const player = new Player(center);
    game.addEntity(player);

    Array.from({ length: dimensions.width })
      .fill(0)
      .map(() => {
        // random grass
        return new Grass({
          x: Math.floor(
            normalRandom(dimensions.width / 2, dimensions.width / 4, 1.5),
          ),
          y: Math.floor(
            normalRandom(dimensions.height / 2, dimensions.height / 4, 1.5),
          ),
        });
      })
      .forEach((e) => game.addEntity(e));
  }
}
