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

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

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

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

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

    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() {
    this._element.addEventListener('change', this._change.bind(this));
  }

  _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();
  }
}
