import Locator from '../services/Locator';
import { Sprite, Texture } from 'pixi.js';
import TextAttachment from './TextAttachment';

export default class SpineButton extends TextAttachment {
  /**
   * @typedef {Object} SpineButtonParams
   * @property {Object} styles - The styles for the button.
   * @property {Spine} container - The container to attach the button to.
   * @property {string} slotID - The slot name in spine.
   * @property {string} localeID - The locale ID in the translations.
   * @property {{ x: number, y: number }} position - Positions for the overlay.
   * @property {Function} onClick - Callback to execute on click.
   */

  /**
   * @param {SpineButtonParams} config
   */
  constructor({ styles, container, slotID, localeID, position, onCLick }) {
    super({
      width: styles.normal.width,
      height: styles.normal.height,
    });

    this._styles = styles;
    this._container = container;
    this._slotID = slotID;
    this._localeID = localeID;
    this._onCLick = onCLick;

    this._init();
    this._createOverlay(position);
  }

  _init() {
    this.text = Locator.locales.get(this._localeID).toUpperCase();
    this.style = this._styles.normal;
    this.attachTo(this._container, this._slotID);
    this.update();
  }

  _createOverlay(pos) {
    const { width, height } = this.textObject;
    const interactiveOverlay = new Sprite(Texture.EMPTY);

    interactiveOverlay.anchor.set(0.5);
    interactiveOverlay.position.x = pos.x;
    interactiveOverlay.position.y = pos.y;
    interactiveOverlay.eventMode = 'static';
    interactiveOverlay.cursor = 'pointer';
    interactiveOverlay.width = width;
    interactiveOverlay.height = height;

    this._overlay = interactiveOverlay;
    this._attachEvents();

    const slotIndex = this._container.skeleton.findSlotIndex(this._slotID);
    const slotContainer = this._container.slotContainers[slotIndex];
    
    slotContainer.addChild(interactiveOverlay);
  }

  _attachEvents() {
    const { normal, hover } = this._styles;

    this._overlay.on('pointerover', () => {
      this.style = hover;
      this.y = -0.5 * hover.strokeThickness;
      this.update();
    });

    this._overlay.on('pointerout', () => {
      this.style = normal;
      this.y = 0;
      this.update();
    });

    this._overlay.on('pointertap', this._onCLick);
  }
}
