class FileLoaderElement extends HTMLElement {
  constructor() {
    super();

    this.addEventListener('dragover', this.onDragOver.bind(this));
    this.addEventListener('dragleave', this.onDragLeave.bind(this));
    this.addEventListener('drop', this.onDrop.bind(this));
  }

  onDrop(evt) {
    evt.preventDefault();
    this.classList.remove('dragover');

    var formData = new FormData();

    [...evt.dataTransfer.items].forEach(function(item) {
      console.log(item.getAsFile());
      formData.append('upload', item.getAsFile());
    });

    var filename = evt.dataTransfer.files[0].name;
    var self = this;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload');
    xhr.send(formData);
    xhr.addEventListener('load', function(evt) {
      try {
        var data = JSON.parse(xhr.responseText);
      } catch(e) {
        var data = {};
      }

      self.dispatchEvent(new CustomEvent("upload_complete", {
        detail: {
          data: data,
          filename: filename
        }
      }));
    });
  }

  onXHRComplete(evt) {
  }

  onDragOver(evt) {
    if(!evt.dataTransfer) return;

    if(Array.from(evt.dataTransfer.items).filter(function(el) {
      if(el.type == 'application/x-extension-fcstd') return el;
    }).length > 0) {
      this.classList.add('dragover');
      evt.preventDefault();
    }
  }

  onDragLeave(evt) {
    this.classList.remove('dragover');
  }

  connectedCallback() {
    this.innerHTML = '<center>Drop File Here<center>';
  }
};

customElements.define('file-loader', FileLoaderElement);
export { FileLoaderElement };
