export class BaseForm {
  constructor(formElement) {
    this.element = formElement;

    this.element.addEventListener('submit', (event) => {
      event.preventDefault();
      this.submit();
    });
    console.log("UsernamePostFormInitialized");
  }

  submit() {
    let errorTextElements = this.element
      .querySelectorAll('.supporting-text[data-supporting-text-type="error"]');
    for (let errorTextElement of errorTextElements) {errorTextElement.remove();}

    const body = new FormData(this.element);
    const headers = {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    };
    const method = this.element.method;

    const fetchPromise = new Promise((resolve, reject) => {
      fetch(this.element.action, {body: body, headers: headers, method: method})
        .then((response) => {
          if (!response.ok) {
            console.log("reject", response);
            reject(response);
            return;
          }
          console.log("resolve", response);
          resolve(response);
        });
    });

    fetchPromise
      .then(
        (response) => {console.log("Hello from resolve handler");return response.json();},
        (response) => {
          console.log("Hello from reject handler 1/2");
          response.json()
            .then((errors) => {
              console.log("Hello from reject handler 2/2");
              for (let [name, messages] of Object.entries(errors)) {
                console.log(name, messages);
                const inputFieldElement = this.element[name].closest('.input-field');
                for (let message of messages) {
                  const messageHTML = `<span class="supporting-text" data-supporting-text-type="error">${message}</span>`;
                  inputFieldElement.insertAdjacentHTML('beforeend', messageHTML);
                }
              }
            });
        }
      );
  }
};