import { Utility } from '../../core/utility';

const FORM_ERROR_REMOVER_INITIALIZED_CLASS = 'form-error-remover--initialized';
const FORM_ERROR_REMOVER_INPUTS_SELECTOR = 'input:not([type="hidden"]), textarea, select';

const FORM_GROUP_SELECTOR = '.form-group';
const FORM_GROUP_WITH_ERRORS_CLASS = 'form-group--has-error';

@Utility({
  selector: 'form',
})
export class FormErrorRemover {

  constructor(element) {
    if (!element) {
      throw new Error('Form Error Remover utility needs to be passed an element!');
    }

    if (element.classList.contains(FORM_ERROR_REMOVER_INITIALIZED_CLASS)) {
      return false;
    }

    // find form groups
    const formGroups = Array.from(element.querySelectorAll(FORM_GROUP_SELECTOR));

    formGroups.forEach((formGroup) => {
      if (!formGroup.classList.contains(FORM_GROUP_WITH_ERRORS_CLASS)) {
        return;
      }

      const inputElements = Array.from(formGroup.querySelectorAll(FORM_ERROR_REMOVER_INPUTS_SELECTOR));
      if (!inputElements) {
        return false;
      }

      inputElements.forEach((inputElement) => {
        inputElement.addEventListener('input', () => {
          formGroup.classList.remove(FORM_GROUP_WITH_ERRORS_CLASS);
        });
      });
    });

    // mark initialized
    element.classList.add(FORM_ERROR_REMOVER_INITIALIZED_CLASS);
  }
}
