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

const FILE_MAX_SIZE_INITIALIZED_CLASS = 'file-max-size--initialized';

@Utility({
  selector: 'input[type="file"][data-max-size]',
})
export class FileMaxSize {
  _element;
  _app;

  _eventManager;

  constructor(element, app) {
    if (!element)
      throw new Error('FileMaxSize utility cannot be setup without an element!');

    this._element = element;
    this._app = app;

    this._eventManager = new EventManager();

    if (this._element.classList.contains(FILE_MAX_SIZE_INITIALIZED_CLASS)) {
      throw new Error('FileMaxSize utility already initialized!');
    }

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

  start() {
    const changeEv = new EventWrapper(EVENT_TYPE.CHANGE, this._change.bind(this), this._element);
    this._eventManager.registerNewListener(changeEv);
  }

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

  _change() {
    const hasOversized = Array.from(this._element.files).some(file => file.size > this._element.dataset.maxSize);
    if (hasOversized) {
      if (this._element.files.length > 1) {
        this._element.setCustomValidity(this._app.i18n.get('fileTooLargeMultiple'));
      } else {
        this._element.setCustomValidity(this._app.i18n.get('fileTooLarge'));
      }
    } else {
      this._element.setCustomValidity('');
    }

    this._element.reportValidity();
  }
}
