import {Polygon} from "pixi.js";
import Locator from "../../services/Locator";

export default class EmbeddedSpineButton {
  constructor(spine, btnName, trackPressed = 0, trackHover = 1) {
    this.spine = spine;
    this.btnName = btnName;
    this.trackPressed = trackPressed;
    this.trackHover = trackHover;
    this.isDisabled = false;
    this.btnSlotIndex = this.spine.skeleton.findSlotIndex(this.btnName);
    this.container = this.spine.slotContainers[this.btnSlotIndex];
    this.bbxSlot = this.spine.skeleton.findSlot(this.btnName + "_bbx");
    this.container.eventMode = "static";
    this.container.name = this.btnName;
    this.container.hitArea = new Polygon(Array.from(this.bbxSlot.attachment.vertices));
    this.container.cursor = "pointer";
    this.container.on("pointerup", () => {
      this.spine.state.setAnimation(trackPressed, this.btnName + "/up", false);
    });
    this.container.on("pointerdown", () => {
      Locator.events.emit("button/click", this.btnName);
      this.spine.state.setAnimation(trackPressed, this.btnName + "/down", false);
    });
    this.container.on("pointerupoutside", () => {
      this.spine.state.setAnimation(trackPressed, this.btnName + "/upoutside", false);
    });
    this.container.on("pointerover", () => {
      Locator.events.emit("button/pointerover");
      this.spine.state.setAnimation(trackHover, this.btnName + "/hover", false);
    });
    this.container.on("pointerout", () => {
      this.spine.state.setAnimation(trackHover, this.btnName + "/out", false);
    });
    this.container.on("click", () => {
    });
  }

  set disabled(v) {
    if (this.isDisabled === v) return;
    if (v) {
      this.disable();
    } else {
      this.enable();
    }
  }

  disable() {
    this.isDisabled = true;
    this.container.eventMode = "none";
    this.spine.state.setAnimation(this.trackHover, this.btnName + "/disable");
  }

  enable() {
    this.isDisabled = false;
    this.container.eventMode = "static";
    this.spine.state.setAnimation(this.trackHover, this.btnName + "/out");
  }

  removeAllListeners() {
    this.container.removeAllListeners();
  }
}
