import BaseSystem from "../systems/BaseSystem";
import BasicWin from "../entities/BasicWin";
import BaseMachine from "../slotMachines/BaseMachine";

export interface DisplayTotalLinesWinSystemSettings {
  zIndex: number,
  entityClass: typeof BasicWin
}

export default class DisplayTotalLinesWinSystem extends BaseSystem<DisplayTotalLinesWinSystemSettings> {
  public state: 'stopped' | 'active' = "stopped";

  private _entity: BasicWin;

  static override requiredInputs = ['wins'];

  static defaultSettings:DisplayTotalLinesWinSystemSettings = {
    zIndex: 100,
    entityClass: BasicWin
  }

  constructor(machine:BaseMachine) {
    super(machine);
    this.setSettings(DisplayTotalLinesWinSystem.defaultSettings);
  }

  get entity() {
    if (!this._entity) {
      this._entity = this.createEntity();
    }
    return this._entity;
  }

  override onEnter() {
    if (!this.getWinsData()) return;
    this.setValue();
    this.show();
  }

  override onLeave() {
    this.hide()
  }

  override update(dt: number) {
    this.entity.update(dt);
  }

  private createEntity() {
    const entity = new this.settings.entityClass();
    entity.zIndex = this.settings.zIndex;
    entity.position.set(0, 0)
    this.machine.addChild(entity);
    this.setCenter(entity);
    entity.visible = false;
    return entity;
  }

  private getWinsData() {
    return this.machine.inputs.wins;
  }

  private setCenter(entity:BasicWin) {
    const x = this.machine.config.width * 0.5;
    const y = this.machine.config.height * 0.5;
    entity.position.set(x, y);
  }

  private setValue() {
    this.entity.value = this.getWinsData().totalWinString
  }

  private show(): void {
    this.entity.visible = true;
    this.entity.show()
  }

  private hide(): void {
    this.entity.hide()
  }

  override destroy() {
    this._entity?.destroy()
  }
}
