const $ = require('jquery');
class Registration {
  constructor(form) {
    this.form = form;
    this.participantTemplate = this.form.find('.row.Participant').clone();
    this.initAddress();
    this.initParticipants();
    this.restoreParticipantsDataFromHistory();
    this.onFormSubmit();
    this.initPollBookingState(0);
  };

  initPollBookingState(pollCount) {
    var that = this;
    var bookingStateUrl = $("#confirmation").data("bookingstate");
    if (bookingStateUrl != undefined) {
      var loops = $("#confirmation").data("loops");
      var timeout = $("#confirmation").data("timeout");
      $.getJSON(bookingStateUrl, function (data) {
        if (data.jsonResponse.bookingstate === "true") {
          $("#confirmation-loading").hide();
          $("#confirmation-success").show();
        } else {
          if (pollCount < loops) {
            setTimeout(function () {
              that.initPollBookingState(++pollCount)
            }, timeout);
          } else {
            $("#confirmation-loading").hide();
            $("#confirmation-error").show();
          }
        }
      });
    }
  }

  initParticipants() {
    const addBtn = this.form.find('.add-participant');

    this.form.find('.row.Participant').remove();

    this.form.on('click', '.remove-participant', (e) => {
      e.preventDefault();
      $(e.currentTarget).closest('.row.Participant').remove();
    });

    addBtn.on('click', () => {
      this.participantTemplate.clone().insertBefore(addBtn.closest('.row'));
    })
  };

  saveParticipantDataInHistory() {
    try {
      const participantsHistoryState = {participants: []};
      const participants = $(".row.Participant");
      participants.each(function () {
        const element = $(this);
        element.wrapInner("<form/>");
        const wrappedForm = element.find("form");
        const formSerializedData = wrappedForm.serializeArray();
        participantsHistoryState.participants.push(formSerializedData);
        $(wrappedForm).children().insertBefore(wrappedForm);
        wrappedForm.remove();

      });

      history.replaceState(participantsHistoryState, document.title);

    } catch (e) {
      console.warn("Could not save Participant data in Navigation History. Error:", e);
    }
  }

  restoreParticipantsDataFromHistory() {
    try {
      if (history.state && history.state.participants) {
        history.state.participants.forEach((historyParticipant,index) => {
          const participantTemplateClone = this.participantTemplate.clone();
          const addBtn = this.form.find('.add-participant');
          historyParticipant.forEach((formField) => {
            const formFieldValue = formField["value"];
            const formFieldName = formField["name"];
            const field =  participantTemplateClone
              .find("[name='" + formFieldName + "']");
            field
              .val(formFieldValue)
              .attr("value",formFieldValue)
              .change()
              .attr("id", null);

            participantTemplateClone.find("[type='hidden']").remove();
          });
          participantTemplateClone.insertBefore(addBtn.closest('.row'));
        })
      }
    } catch (e) {
      console.warn("Could not restore Participant data from Navigation History. Error:", e);
    }
  }

  onFormSubmit() {
    this.form.find(".submit").on("click", (e) => {
      const invalidFields = this.form.find(":invalid");
      if(invalidFields.length > 0){
        this.scrollToInvalidFieldOnSubmit();
      } else {
        e.preventDefault();
        this.saveParticipantDataInHistory();
        this.form.submit();
      }
    })
  }

  scrollToInvalidFieldOnSubmit() {
    const invalidFields = this.form.find(":invalid");
    $('html, body').animate({
      scrollTop: invalidFields.first().offset().top - 150
    }, 10);
  };

  initAddress() {
    const diffAddress = this.form.find(".rechnungAnPrivatAdresse");
    const addressToggler = this.form.find('#vst_abweichend_check');

    if (addressToggler.prop('checked')) {
      diffAddress.show();
    }

    addressToggler.on('change', (e) => {
      if ($(e.currentTarget).prop('checked')) {
        diffAddress.stop().slideDown(400, 'easeOutQuad');
        this.setMandatory(diffAddress, true);
        $('#vst_abweichend_val').val("false");
      } else {
        diffAddress.stop().slideUp(400, 'easeOutQuad');
        this.setMandatory(diffAddress, false);
        $('#vst_abweichend_val').val("true");
      }
    });

    this.setMandatory(diffAddress, diffAddress.is(':visible'));
  };

  setMandatory(wrapper, visible) {
    const inputs = wrapper.find('.mandatory');
    if (visible) {
      inputs.prop('required', 'true');
    } else {
      inputs.removeAttr('required');
    }
  };
}


$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.vst-registration:not(.initialized)').each(function () {
    $('.vst-registration').addClass("initialized");
    new Registration($(this));
  });

  $('#confirmation:not(.initialized)').each(function () {
    $('#confirmation').addClass("initialized");
    new Registration($(this));
  });

  // TODO
  if ($('#captcha-wrapper:not(.initialized)').length > 0  ) {
    $('#captcha-wrapper').addClass("initialized");
    window.gfiWebforms.initCaptcha();
  }

});
