// SPDX-FileCopyrightText: 2022 Gregor Kleen <gregor.kleen@ifi.lmu.de>,Sarah Vaupel <sarah.vaupel@ifi.lmu.de>,Sarah Vaupel <vaupel.sarah@campus.lmu.de>
//
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Utility } from '../../core/utility';
import { EventManager, EventWrapper, EVENT_TYPE } from '../../lib/event-manager/event-manager';

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_WITH_ERRORS_CLASSES = ['form-group--has-error', 'standalone-field--has-error'];
const FORM_GROUP_SELECTOR = FORM_GROUP_WITH_ERRORS_CLASSES.map(c => '.' + c).join(', ');

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

  _element;

  _eventManager;

  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;

    if (FORM_GROUP_WITH_ERRORS_CLASSES.every(c => !element.classList.contains(c)))
      return;

    this._element = element;
    this._eventManager = new EventManager();
    
    this._element.classList.add(FORM_ERROR_REMOVER_INITIALIZED_CLASS);
  }

  start() {
    if (!this._element)
      return;

    const inputElements = Array.from(this._element.querySelectorAll(FORM_ERROR_REMOVER_INPUTS_SELECTOR));

    inputElements.forEach((inputElement) => {
      const inputEvent = new EventWrapper(EVENT_TYPE.INPUT, (() => {
        if (!inputElement.willValidate || inputElement.validity.vaild) {
          FORM_GROUP_WITH_ERRORS_CLASSES.forEach(c => { this._element.classList.remove(c); });
        }
      }).bind(this), inputElement);
      this._eventManager.registerNewListener(inputEvent);
    });
  }

  destroy() {
    this._eventManager.cleanUp();
    this._element.classList.remove(FORM_ERROR_REMOVER_INITIALIZED_CLASS);
  }

}
