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

export default class EmbeddedSpineCheckbox {
  constructor(spine, checkboxName, trackPressed = 0, trackHover = 1, trackChecked = 2) {
    this.spine = spine;
    this.checkboxName = checkboxName;
    this.tracks = {
      trackPressed,
      trackHover,
      trackChecked
    };

    this.btnSlotIndex = this.spine.skeleton.findSlotIndex(this.checkboxName);
    this.container = this.spine.slotContainers[this.btnSlotIndex];
    this.bbxSlot = this.spine.skeleton.findSlot(this.checkboxName + "_bbx");
    this.container.eventMode = "static";
    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.checkboxName + "/up", false);
      this.toggle();
    });
    this.container.on("pointerdown", () => {
      this.spine.state.setAnimation(trackPressed, this.checkboxName + "/down", false);
    });
    this.container.on("pointerupoutside", () => {
      this.spine.state.setAnimation(trackPressed, this.checkboxName + "/upoutside", false);
    });
    this.container.on("pointerover", () => {
      this.spine.state.setAnimation(trackHover, this.checkboxName + "/hover", false);
      Locator.events.emit("button/pointerover");
    });
    this.container.on("pointerout", () => {
      this.spine.state.setAnimation(trackHover, this.checkboxName + "/out", false);
    });
    this.container.on("click", () => {
      Locator.events.emit("button/click", this.checkboxName);
    });
  }

  get checked() {
    return this._checked;
  }

  set checked(value) {
    value = !!value;
    if (this._checked === value) return;
    this._checked = value;
    if (this._checked) {
      this.spine.state.setAnimation(this.tracks.trackChecked, this.checkboxName + "/checked");
    } else {
      this.spine.state.setAnimation(this.tracks.trackChecked, this.checkboxName + "/unchecked");
    }
  }

  toggle() {
    this.checked = !this.checked;
  }
}
