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

export const AUTO_SUBMIT_INPUT_UTIL_SELECTOR = '[uw-auto-submit-input]';

const AUTO_SUBMIT_INPUT_INITIALIZED_CLASS = 'auto-submit-input--initialized';

@Utility({
  selector: AUTO_SUBMIT_INPUT_UTIL_SELECTOR,
})
export class AutoSubmitInput {

  _element;

  _eventManager;

  _form;
  _debouncedHandler;

  constructor(element) {
    if (!element) {
      throw new Error('Auto Submit Input utility needs to be passed an element!');
    }

    this._element = element;

    this._eventManager = new EventManager();

    if (this._element.classList.contains(AUTO_SUBMIT_INPUT_INITIALIZED_CLASS)) {
      return false;
    }

    this._form = this._element.form;
    if (!this._form) {
      throw new Error('Could not determine associated form for auto submit input');
    }

    this._debouncedHandler = debounce(this.autoSubmit, 500);

    const inputEvent = new EventWrapper(EVENT_TYPE.INPUT, this._debouncedHandler.bind(this), this._element);
    this._eventManager.registerNewListener(inputEvent);

    this._element.classList.add(AUTO_SUBMIT_INPUT_INITIALIZED_CLASS);
  }

  destroy() {
    this._eventManager.removeAllEventListenersFromUtil();
    if(this._element.classList.contains(AUTO_SUBMIT_INPUT_INITIALIZED_CLASS))
      this._element.classList.remove(AUTO_SUBMIT_INPUT_INITIALIZED_CLASS);
  }

  autoSubmit = () => {
    this._form.submit();
  }
}
