import { Entity, EntityNames, Particles } from ".";
import { Game } from "..";
import {
  BoundingBox,
  Colliding,
  Grid,
  Sprite,
  ComponentNames,
} from "../components";
import {
  IMAGES,
  KeyOpen,
  SOUNDS,
  SPRITE_SPECS,
  SpriteSpec,
  Sprites,
} from "../config";
import { Coord2D } from "../interfaces";
import { Grid as GridSystem, SystemNames } from "../systems";
import { colors } from "../utils";

export class LockedDoor extends Entity {
  private static spriteSpec: SpriteSpec = SPRITE_SPECS.get(
    Sprites.LOCKED_DOOR
  ) as SpriteSpec;

  constructor(gridPosition: Coord2D) {
    super(EntityNames.LockedDoor);

    this.addComponent(new Grid(gridPosition));

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

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

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

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

    game.removeEntity(this.id);
    game.removeEntity(entity.id);

    const grid = this.getComponent<Grid>(ComponentNames.Grid);
    const gridSystem = game.getSystem<GridSystem>(SystemNames.Grid);
    const { dimension } = gridSystem;
    const particles = new Particles({
      center: gridSystem.gridToScreenPosition(grid.gridPosition),
      spawnerDimensions: {
        width: dimension.width / 2,
        height: dimension.height / 2,
      },
      particleCount: 20,
      spawnerShape: "rectangle",
      particleShape: "rectangle",
      particleMeanSpeed: 0.35,
      particleSpeedVariance: 0.15,
      particleMeanLife: 80,
      particleMeanSize: 3,
      particleSizeVariance: 1,
      particleLifeVariance: 20,
      particleColors: [colors.yellow, colors.lightYellow],
    });

    game.addEntity(particles);

    this.playKeySound();
  }

  private playKeySound() {
    const audio = SOUNDS.get(KeyOpen.name)!;
    audio.play();
  }
}
