import { System, SystemNames } from ".";
import {
  ComponentNames,
  Grid,
  RadialObserve as RadialObserveComponent,
} from "../components";
import { Entity, EntityNames } from "../entities";
import { Game } from "../Game";
import { cartesianDistance } from "../interfaces";

const radialObservations: Record<string, Set<string>> = {
  [EntityNames.Piston]: new Set([EntityNames.FunctionBox]),
};

export class RadialObserve extends System {
  constructor() {
    super(SystemNames.RadialObserve);
  }

  public update(_dt: number, game: Game) {
    game.forEachEntityWithComponent(ComponentNames.RadialObserve, (entity) => {
      if (!(entity.name in radialObservations)) {
        return;
      }
      const observable = radialObservations[entity.name];

      const entityObserve = entity.getComponent<RadialObserveComponent>(
        ComponentNames.RadialObserve,
      );
      if (!entityObserve.onObservation) {
        return;
      }

      const entityPosition = entity.getComponent<Grid>(
        ComponentNames.Grid,
      ).gridPosition;

      const observations: Entity[] = [];
      game.forEachEntityWithComponent(ComponentNames.RadialObserve, (other) => {
        if (entity === other) {
          return;
        }
        if (!observable.has(other.name)) {
          return;
        }

        const otherPosition = other.getComponent<Grid>(
          ComponentNames.Grid,
        ).gridPosition;
        if (
          cartesianDistance(entityPosition, otherPosition) >
          entityObserve.radius
        ) {
          return;
        }

        observations.push(other);
      });

      for (const observation of observations) {
        entityObserve.onObservation!(game, observation);
      }
    });
  }
}
