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

export default class EmbeddedSpineSlider {
  constructor(spine, sliderName) {
    this.spine = spine;
    this.name = sliderName;

    this.barSlotIndex = this.spine.skeleton.findSlotIndex(this.name + "_bar");
    this.barContainer = this.spine.slotContainers[this.barSlotIndex];
    this.barContainer.eventMode = "dynamic";
    this.barBbxSlot = this.spine.skeleton.findSlot(this.name + "_bar_bbx");
    this.barContainer.hitArea = new Polygon(Array.from(this.barBbxSlot.attachment.vertices));

    this.pathConstrait = this.spine.skeleton.findPathConstraint("slider_volume_path");


    this.length = this.barContainer.width;

    this.barContainer.on("pointerdown", this.handlePointerDown, this);
  }

  get position() {
    return this.pathConstrait.position;
  }

  set position(value) {
    if (value < 0) {
      value = 0;
    } else if (value > 1) {
      value = 1;
    }
    this.spine.spineData.findPathConstraint("slider_volume_path").position = value;
    this.pathConstrait.position = value;
  }

  onchange() {

  }

  ondown() {

  }

  onup() {

  }

  handlePointerDown(e) {
    const localPointerPosition = this.barContainer.toLocal(e.global);
    this.position = this.calculatePosition(localPointerPosition.x);
    Locator.events.on("globalpointermove", this.handlePointerMove, this);
    Locator.events.on("globalpointerup", this.handlePointerUp, this);
    this.ondown({value: this.position});
  }

  handlePointerUp() {
    Locator.events.off("globalpointermove", this.handlePointerMove, this);
    Locator.events.off("globalpointerup", this.handlePointerUp, this);
    this.onup({value: this.position});
  }

  handlePointerMove(e) {
    const localPointerPosition = this.barContainer.toLocal(e.global);
    this.position = this.calculatePosition(localPointerPosition.x);
    this.onchange({value: this.position});
  }

  calculatePosition(localX) {
    return (localX + this.length * 0.5) / this.length;
  }

}
