import $ from 'domtastic';
import Popper from 'popper.js';
import ToggleComponent from '../_helpers/toggleComponent';

export default class Confirm extends ToggleComponent {
  constructor(element, customOptions) {
    const $popup = $(element);

    let options = {
      target: $(`[data-sui-o-popup="${$popup.attr('id')}"]`).first(),
      dataAttrBase: 'data-sui-o-popup',
      clickOutsideEnabled: true,
      focusRecoverEnabled: true,
      placement: 'top',
    };

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

    super($popup, options);
  }

  _onDestroy() {
    super._onDestroy();

    if (this.popper) {
      this.popper.destroy();
    }
  }

  _onOpen(clickedElement) {
    this.selectedItem = -1;

    const $target = clickedElement ? $(clickedElement) : $(this.options.target);
    const $popup = this.$component;

    if (this.popper) {
      this.popper.destroy();
    }

    if ($target && $target[0] && $popup && $popup[0]) {
      this.popper = new Popper($target[0], $popup[0], {
        placement: this.options.placement,
      });
    }

    super._onOpen();
  }
}
