import Dropzone from "dropzone";
import $ from 'jquery';

class FileInfoDropzone {
  constructor(element, dropzoneClass) {
    const DropzoneClass = dropzoneClass || Dropzone

    this.myDropzone = this.createDropzone(element, DropzoneClass)

    this.addExistingFiles(this.myDropzone, element);
  }

  addExistingFiles(dropzone, element) {
    const files = $(element).data("existingFiles") || []
    files.forEach((file, index) => {
      dropzone.emit("addedfile", file);

      dropzone.emit("complete", file);
    })
  }

  createDropzone(element, DropzoneClass) {
    const acceptedFiles = $(element).data("accepted-files");
    const dictDefaultMessage = $(element).data("placeholder") || "Drop files here";
    const inputPrefix = $(element).data("input-name-prefix")

    return new DropzoneClass(element, {
      url: "/",
      acceptedFiles: acceptedFiles,
      autoQueue: true,
      parallelUploads: 30,
      dictDefaultMessage: dictDefaultMessage,
      maxFilesize: null,

      init: function () {
        this.on("sending", (file, xhr, formData) => {
          const index = Date.now();
          let hiddenField = document.createElement('input');
          hiddenField.setAttribute("type", "hidden");
          hiddenField.setAttribute("value", file.name);
          hiddenField.name = `${inputPrefix}[${index}][filename]`;
          document.querySelector('form').appendChild(hiddenField);

          hiddenField = document.createElement('input');
          hiddenField.setAttribute("type", "hidden");
          hiddenField.setAttribute("value", file.type);
          hiddenField.name = `${inputPrefix}[${index}][content_type]`;
          document.querySelector('form').appendChild(hiddenField);

          hiddenField = document.createElement('input');
          hiddenField.setAttribute("type", "hidden");
          hiddenField.setAttribute("value", file.size);
          hiddenField.name = `${inputPrefix}[${index}][byte_size]`;
          document.querySelector('form').appendChild(hiddenField);

          this.emit("success", file);
          this.emit("complete", file);

          // Cancel the default server request
          xhr.addEventListener("loadstart", () => {
            xhr.abort();
          });
        });
      },
    });
  }
}

Dropzone.autoDiscover = false;

export default FileInfoDropzone;

document.addEventListener("turbolinks:load", function () {
  $("[data-behavior=file-info-dropzone]").each(function (index, element) {
    new FileInfoDropzone(element)
  });
});
