var Wick = 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 = Wick.GenerateProjectId.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);
      })
  },
  addProjectId(projectId) {
    $(Wick.GenerateProjectId.el.generateBtn).addClass(Wick.GenerateProjectId.el.selectableBtn);
    $(Wick.GenerateProjectId.el.generateBtn).html(`ID: ${projectId}`);
    $(Wick.GenerateProjectId.el.generateBtn).off('click', Wick.GenerateProjectId.generateId);
    $(Wick.GenerateProjectId.el.generateBtn).blur();
  },
  createEvent(eventName, payload, eventDetail) {
    return new CustomEvent(eventName, {
      detail: {
        payload,
        resolve: eventDetail.resolve,
        reject: eventDetail.reject,
      },
    });
  },
  init() {
    $(Wick.GenerateProjectId.el.generateBtn).on('click', Wick.GenerateProjectId.generateId)
  },
};

$(document).ready(function () {
  if (!Wick.GenerateProjectId.el.generateBtn.length) {
    return;
  }

  Wick.GenerateProjectId.init();
});
