import { Entity, EntityNames } from ".";
import { Game } from "..";
import { BoundingBox, Colliding, Grid, Sprite, Text } from "../components";
import { IMAGES, SPRITE_SPECS, SpriteSpec, Sprites } from "../config";
import { Coord2D } from "../interfaces";
import { Level, SystemNames } from "../systems";

export class Portal extends Entity {
  private static spriteSpec = SPRITE_SPECS.get(Sprites.PORTAL) as SpriteSpec;

  private toLevel: string;

  constructor(toLevel: string, gridPosition: Coord2D) {
    super(EntityNames.Portal);

    this.toLevel = toLevel;

    this.addComponent(
      new BoundingBox(
        {
          x: 0,
          y: 0,
        },
        {
          width: Portal.spriteSpec.width,
          height: Portal.spriteSpec.height,
        },
        0
      )
    );

    this.addComponent(
      new Sprite(
        IMAGES.get(Portal.spriteSpec.sheet)!,
        { x: 0, y: 0 },
        {
          width: Portal.spriteSpec.width,
          height: Portal.spriteSpec.height,
        },
        Portal.spriteSpec.msPerFrame,
        Portal.spriteSpec.frames
      )
    );

    this.addComponent(new Colliding(this.handleCollision.bind(this)));

    this.addComponent(new Grid(gridPosition));

    this.addComponent(new Text(toLevel));
  }

  public handleCollision(game: Game, entity: Entity) {
    if (entity.name !== EntityNames.Player) {
      return;
    }

    const levelSystem = game.getSystem<Level>(SystemNames.Level);
    levelSystem.setLevel(this.toLevel);
  }
}
