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) {
    const currentState = Wick.LeaveEvent.getState(form);
    const isDifferent = !_.isEqual(currentState, Wick.LeaveEvent.initialFormState);

    if (isDifferent) {
      e.preventDefault();
      Wick.LeaveEvent.showCustomModal();
      Wick.LeaveEvent.proceedBrowserLeave = false;
    }
  },
  makeLeaveByBrowser(form) {
    const currentState = Wick.LeaveEvent.getState(form);
    const isDifferent = !_.isEqual(currentState, Wick.LeaveEvent.initialFormState);

    if (isDifferent) {
      return Wick.LeaveEvent.LEAVE_MESSAGE;
    }
  },
  showCustomModal() {
    $(Wick.LeaveEvent.el.leavePopup).modal('show')
  },
  getState(form) {
    return $(form).serializeArray();
  },
  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) {
    Wick.LeaveEvent.initialFormState = Wick.LeaveEvent.getState(form);
    Wick.LeaveEvent.el.form = form;

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

    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();
      });
    }

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

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