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

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

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

  private _entity: BasicWin;

  static override requiredInputs = ['wins'];
  static override sharedSystemData = ['currentWinIndex'];

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

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

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

  override onEnter() {
    if (!this.getWinsData()) return;
    this.setValue();
    this.setPosition();
    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);
    entity.visible = false;
    return entity;
  }

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

  private setPosition() {
    const currentWinIndex = this.getCurrentWinIndex();
    const currentWinData = this.getWinsData().wins[currentWinIndex];
    const lineMap = this.machine.config.lines[currentWinData.lineIndex];
    const slotIndex = lineMap[Math.floor(lineMap.length / 2)];
    const mapIndex = this.machine.utils.grid.fromCRtoMapIndex(0, slotIndex);
    const position = this.machine.utils.grid.fromMapIndexToXY(mapIndex)
    const x = this.machine.config.width * 0.5;
    const y = position.y;
    this.entity.position.set(x, y);
  }

  private setValue() {
    this.entity.value = this.getWinsData().wins[this.getCurrentWinIndex()].amountString;
  }

  private getCurrentWinIndex() {
    return this.machine.sharedSystemData.currentWinIndex
  }

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

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

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