var Wick = window.Wick || {};
Wick.LeaveEvent = {
  LEAVE_MESSAGE: 'Data you have entered on this page will not be saved',
  el: {
    leavePopup: '#leave-popup',
    confirmLeaveBtn: "btn-confirm-leave",
    form: null,
  },
  proceedBrowserLeave: true,
  initialFormState: {},
  makeLeaveByAction(e, form, callback) {
    const currentState = Wick.LeaveEvent.getState(form);
    const isDifferent = !_.isEqual(currentState, Wick.LeaveEvent.initialFormState);

    if (isDifferent) {
      e.preventDefault();
      Wick.LeaveEvent.showCustomModal();
      Wick.LeaveEvent.proceedBrowserLeave = false;
    }

    if (callback && !isDifferent) {
      callback();
    }
  },
  makeLeaveByBrowser(form) {
    const currentState = Wick.LeaveEvent.getState(form);
    const isDifferent = !_.isEqual(currentState, Wick.LeaveEvent.initialFormState);

    const csrfTokenCheck = Wick.LeaveEvent.isCsrfTokenEqual(currentState, Wick.LeaveEvent.initialFormState);

    if (isDifferent && (csrfTokenCheck || csrfTokenCheck === undefined)) {
      return Wick.LeaveEvent.LEAVE_MESSAGE;
    }
  },
  isCsrfTokenEqual(currentState, initialFormState) {
    const csrfTokenCurrentState = currentState.find(item => item.name === 'CSRFToken')?.value;
    const csrfTokenNewState = initialFormState.find(item => item.name === 'CSRFToken')?.value;

    return csrfTokenCurrentState === csrfTokenNewState;
  },
  showCustomModal() {
    $(Wick.LeaveEvent.el.leavePopup).modal('show')
  },
  getState(form) {
    let arrForm = $(form).serializeArray();
    arrForm = Wick.LeaveEvent.processSerializedArr(arrForm, form);
    return arrForm;
  },
  processSerializedArr(arrForm, form) {
    arrForm = arrForm.filter(item => {
      let element = $(form).find(`[name="${item.name}"]`);
      return item.name !== "g-recaptcha-response" && element.attr("type") !== "hidden";
    });

    arrForm = arrForm.map((item) => {
      let element = $(form).find(`[name="${item.name}"]`);

      if (element.attr("data-tag")) {
        let dataTagValue = element.attr("data-tag");
        let similarElements = $(form).find(`[data-tag="${dataTagValue}"]`);
        let hiddenElement = similarElements.filter(`[type="hidden"]`);

        if (hiddenElement.length) {
          let previousElement = similarElements.not(`[type="hidden"]`);
          let previousValue = previousElement.val();
          item.value = hiddenElement.val();
          item.text = previousValue;
        }
      } else if (element.prop("tagName").toLowerCase() === "select") {
        item.value = element.find("option:selected").val();
        item.text = element.find("option:selected").text();
      }

      if (item.name === "email" && item.value) {
        item.value = item.value.toLowerCase();
      }

      return item;
    });

    return arrForm;
  },
  checkLeavePopup() {
    if (Wick.LeaveEvent.proceedBrowserLeave) {
      return Wick.LeaveEvent.makeLeaveByBrowser(Wick.LeaveEvent.el.form);
    }
  },
  removeLeaveEvent() {
    $(window).off('beforeunload', Wick.LeaveEvent.checkLeavePopup);
  },
  bindEvent(form = 'form', leaveBtn, submitBtn, callback) {
    Wick.LeaveEvent.initialFormState = Wick.LeaveEvent.getState(form);
    Wick.LeaveEvent.el.form = form;

    $(leaveBtn).on('click', (e) => {
      Wick.LeaveEvent.makeLeaveByAction(e, form, callback);
    });

    if ($(Wick.LeaveEvent.el.leavePopup).length) {
      $(Wick.LeaveEvent.el.leavePopup).on("hide.bs.modal", function () {
        Wick.LeaveEvent.proceedBrowserLeave = true;
      });
    }

    if ($(submitBtn).length) {
      $(submitBtn).on('click', (e) => {
        Wick.LeaveEvent.removeLeaveEvent();
        if (callback) {
          callback();
        }
      });
    }

    $(window).on('beforeunload', Wick.LeaveEvent.checkLeavePopup);

    $(window).on('unload', function () {
      Wick.LeaveEvent.removeLeaveEvent();
    });
  }
};
