import {copyToClipboard} from "../utils/copy-to-clipboard";
import {createEvent} from "../utils/create-event";

var Wick = window.Wick || {};
Wick.GenerateProjectId = {
  GENERATE_PROJECT_ID_EVENT: 'generateProjectId',
  el: {
    generateBtn: '.generate-project-id__btn',
    selectableBtn: 'generate-project-id__btn--selectable',
    pendingBtn: 'btn-pending',
  },
  generateId() {
    $(Wick.GenerateProjectId.el.generateBtn).addClass(Wick.GenerateProjectId.el.pendingBtn);

    return new Promise((resolve, reject) => {

      const payload = {};
      const eventDetail = {resolve, reject};
      const event = createEvent(Wick.GenerateProjectId.GENERATE_PROJECT_ID_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(({projectId}) => {
        Wick.GenerateProjectId.addProjectId(projectId);
      })
      .catch(({errorMessage}) => {
        Wick.Notification.show({
          text: errorMessage,
          container: '.globalMessages .col-12',
          type: 'error',
          closeBtn: true,
          noScrolling: true,
        });
      })
      .finally(() => {
        $(Wick.GenerateProjectId.el.generateBtn).removeClass(Wick.GenerateProjectId.el.pendingBtn);
      })
  },
  copyProjectIdToClipboard(projectId) {
    copyToClipboard(projectId, Wick.GenerateProjectId.el.generateBtn);
    Wick.Notification.show({
      text: Wick.CopyProjectId.NOTIFICATION_TEXT,
      container: '.globalMessages .col-12',
      type: 'success',
      closeBtn: true,
      noScrolling: true,
    });
  },
  addProjectId(projectId) {
    const btnText = $(Wick.GenerateProjectId.el.generateBtn).find('.btn-transparent__text');
    btnText.text(`${projectId}`);
    const downloadIcon = $(Wick.GenerateProjectId.el.generateBtn).find('.btn-transparent__icon');
    const copyIcon = $(this.el.generateBtn).find('.copy-barcode');
    downloadIcon.remove();

    copyIcon.show();
    $(Wick.GenerateProjectId.el.generateBtn).off('click', Wick.GenerateProjectId.generateId).on('click', (e) => {
      e.preventDefault();
      this.copyProjectIdToClipboard(projectId);
    });

    $(Wick.GenerateProjectId.el.generateBtn).addClass(Wick.GenerateProjectId.el.selectableBtn);
    $(Wick.GenerateProjectId.el.generateBtn).off('click', Wick.GenerateProjectId.generateId);
    $(Wick.GenerateProjectId.el.generateBtn).blur();
  },
  init() {
    $(Wick.GenerateProjectId.el.generateBtn).on('click', Wick.GenerateProjectId.generateId)
  },
};

$(document).ready(function() {
  if ($(Wick.GenerateProjectId.el.generateBtn).length) {
    Wick.GenerateProjectId.init();
  }
  if ($(Wick.GenerateProjectId.el.selectableBtn).length) {
    $(document).on('click', Wick.GenerateProjectId.el.generateBtn, function() {
      Wick.GenerateProjectId.generateId();
    });
  }
});
