import $ from 'domtastic';
import PopperTooltip from 'tooltip.js';

export default class Tooltip {
  constructor(element, customOptions) {
    this.$tooltip = $(element);

    this.options = {
      title: this.$tooltip.attr('data-sui-a-tooltip'),
      placement: 'top',
      classes: '',
      disableHtmlToBody: false,
    };

    // Merge custom options
    if (customOptions) {
      this.options = $.extend({}, this.options, customOptions);
    }
  }

  init() {
    if (this.popperTooltip) {
      this.destroy();
    }

    const { $tooltip } = this;

    if (!$tooltip || !$tooltip[0]) {
      return this;
    }

    const container = this.options.disableHtmlToBody ? false : $('body')[0];

    this.popperTooltip = new PopperTooltip($tooltip[0], {
      placement: this.options.placement,
      title: this.options.title,
      container,
      template: `<div class="sui-a-tooltip tooltip ${this.options.classes}" role="tooltip"><div class="sui-a-tooltip__arrow tooltip-arrow"></div><div class="sui-a-tooltip__inner tooltip-inner"></div></div>`,
    });

    return this;
  }

  toggle() {
    if (this.popperTooltip) {
      this.popperTooltip.toggle();
    }

    return this;
  }

  open() {
    if (this.popperTooltip) {
      this.popperTooltip.show();
    }

    return this;
  }

  close() {
    if (this.popperTooltip) {
      this.popperTooltip.hide();
    }

    return this;
  }

  destroy() {
    if (this.popperTooltip) {
      this.popperTooltip.dispose();
    }

    return this;
  }
}
