import { SystemNames, System } from ".";
import { Game } from "..";
import { type Level as LevelType, LEVELS, LEVEL_PROGRESSION } from "../levels";

export class Level extends System {
  private unlockedLevels: Set<string>;
  private currentLevel: LevelType | null;
  private moveToLevel: string | null;
  private levelMap: Map<string, LevelType>;

  constructor(initialLevel: string) {
    super(SystemNames.Level);

    this.levelMap = new Map();
    LEVELS.forEach((level) => {
      this.levelMap.set(level.name, level);
    });

    this.currentLevel = null;
    this.moveToLevel = initialLevel;
    this.unlockedLevels = new Set();
  }

  public setLevel(level: string) {
    this.moveToLevel = level;
  }

  public update(_dt: number, game: Game) {
    if (this.moveToLevel === this.currentLevel?.name || !this.moveToLevel) {
      return;
    }

    if (this.currentLevel) {
      game.resetState();
    }

    const unlockedLevels = LEVEL_PROGRESSION[this.moveToLevel];
    if (unlockedLevels && unlockedLevels.length > 0) {
      unlockedLevels.forEach((levelName) => {
        if (!this.unlockedLevels.has(levelName)) {
          this.unlockedLevels.add(levelName);
        }
      });
    }

    if (!this.unlockedLevels.has(this.moveToLevel)) {
      this.unlockedLevels.add(this.moveToLevel);
    }
    this.currentLevel = this.levelMap.get(this.moveToLevel)!;
    this.currentLevel.init(game);
    this.moveToLevel = null;
  }

  public getUnlockedLevels() {
    return this.unlockedLevels;
  }
}
