/* global recaptchaCallback */

class WpjForm {

   constructor() {
      this.formSelector = '[data-form]';
      this.submitButtonSelector = '[data-form-submit]';
   }

   init() {
      const self = this;
      document.querySelectorAll(this.formSelector).forEach((form) => {
         const submitButton = form.querySelector(this.submitButtonSelector);
         if (!submitButton) {
            return;
         }

         self.registerSubmitButton(form, submitButton);
      });
   }

   registerSubmitButton(form, submitButton) {
      const self = this;

      submitButton.addEventListener('click', () => {
         const type = form.dataset.form;
         const data = self.collectFormData(form);

         self.sendForm(type, data)
            .then((response) => {
               response.text().then((text) => {
                  // update content
                  form.innerHTML = text;

                  // reinit pro captchu
                  if (typeof recaptchaCallback === 'function') {
                     recaptchaCallback();
                  }

                  // reinit pro submit button
                  const newSubmitButton = form.querySelector(this.submitButtonSelector);
                  if (newSubmitButton) {
                     self.registerSubmitButton(form, newSubmitButton);
                  }
               })
            });

         return false;
      });
   }

   sendForm(type, data) {
      const endpoint = '/formulare/' + type + '/';

      return fetch(endpoint, {
         method: 'POST',
         redirect: 'follow',
         body: data,
      });
   }

   collectFormData(form) {
      const formData = new FormData();

      form.querySelectorAll('[name]').forEach((input) => {
         formData.append(input.getAttribute('name'), input.value);
      });

      return formData;
   }
}

const wpjForm = new WpjForm();
wpjForm.init();
