import {
  ComponentNames,
  FacingDirection as FacingDirectionComponent,
  BoundingBox,
  Sprite,
} from "../components";
import { Game } from "../Game";
import { System, SystemNames, Input } from ".";
import { Direction, angleToDirection } from "../interfaces";

export class FacingDirection extends System {
  private input: Input;

  constructor(input: Input) {
    super(SystemNames.FacingDirection);

    this.input = input;
  }

  public update(_dt: number, game: Game) {
    const mousePosition = this.input.getMousePosition();
    const mouseBoundingBox = new BoundingBox(mousePosition, {
      width: 0,
      height: 0,
    });

    game.forEachEntityWithComponent(
      ComponentNames.FacingDirection,
      (entity) => {
        if (!entity.hasComponent(ComponentNames.BoundingBox)) {
          return;
        }

        const boundingBox = entity.getComponent<BoundingBox>(
          ComponentNames.BoundingBox
        )!;
        const facingDirection = entity.getComponent<FacingDirectionComponent>(
          ComponentNames.FacingDirection
        );

        const { center } = boundingBox;
        const angle = Math.atan2(
          mousePosition.y - center.y,
          mousePosition.x - center.x
        );

        const mouseInBoundingBox =
          boundingBox.isCollidingWith(mouseBoundingBox);
        const direction = mouseInBoundingBox
          ? Direction.NONE
          : angleToDirection(angle);

        facingDirection.setDirection(direction);
        entity.addComponent(facingDirection);

        const oldSprite = entity.getComponent<Sprite>(ComponentNames.Sprite);
        const sprite = facingDirection.directionSprites.get(direction)!;
        sprite.fillTimingsFromSprite(oldSprite);

        entity.addComponent(sprite);
      }
    );
  }
}
