//Disabling autoDiscover
Dropzone.autoDiscover = false;

jQuery(function($) {


  $( ".dropzone" ).each(function() {
    var elid = "#"+ $(this).attr("id");
    var id = $(this).data("id");
    var maxFiles = $(this).data("maxFiles");
    var maxSize = $(this).data("maxSize");
    var msg = $(this).data("msg");
    // each instance

    var fileList = [];
      //Dropzone class
    var myDropzone = new Dropzone(elid, {
      url: "app/includes/ajax.php",
      paramName: "file",
      withCredentials: true,
      maxFilesize: maxSize,
      maxFiles: maxFiles,
      // forceFallback: true,
      thumbnailMethod: "crop",
      dictRemoveFile: '<i class="fas fa-times"><i>',
      acceptedFiles: $(elid).data("accepts"),
      extensions: $(elid).data("exts"),
      addRemoveLinks: true,
      dictDefaultMessage: msg,
      init: function() {
            var thisDropzone = this;
            var ref = $(elid+" #ref-"+id).val();
            var user_id = $(elid+" #user_id-"+id).val();
            $.ajax({
                type: 'POST',
                url: 'app/includes/ajax.php',
                data: {"action": "get_library_files", "ref" : ref, "user_id" : user_id},
                success: function(data) {
                  data = JSON.parse(data);
                  $.each(data.files, function(key,value){
                    fileList[value.ctrlid] = {"serverFileName" : value.file_name, "library_id": data.library_id };
                    var mockFile = { name: value.title, _url: value.file_name, _file_type: value.file_type, size: value.size, ctrlid: value.ctrlid, status: "added", accepted: true, previewTemplate: thisDropzone.previewTemplate };
                    thisDropzone.options.addedfile.call(thisDropzone, mockFile);
                    thisDropzone.options.thumbnail.call(thisDropzone, mockFile, value.file_name);
                    thisDropzone.options.complete.call(thisDropzone, mockFile);
                    thisDropzone.files.push( mockFile );
                    var e = $('img[src="'+value.file_name+'"]');
                    var ext = value.file_name.split('.').pop();
                    if (ext == "pdf") {
                        $(e).replaceWith('<img src="app/assets/js/dropzone/img/pdf-icon.png">');
                    } else if (ext.indexOf("doc") != -1) {
                        $(e).replaceWith('<img src="app/assets/js/dropzone/img/word-icon.png">');
                    } else if (ext.indexOf("xls") != -1) {
                        $(e).replaceWith('<img src="app/assets/js/dropzone/img/excel-icon.png">');
                    }
                    

                  });
                },
                error: function(xhr, status, error) {
                }
            });
        }
    });

    myDropzone.on('addedfile', function(file) {
        var ext = file.name.split('.').pop();
        if (ext == "pdf") {
            $(elid).find(file.previewElement).find(".dz-image img").replaceWith('<img src="app/assets/js/dropzone/img/pdf-icon.png">');
        } else if (ext.indexOf("doc") != -1) {
            $(elid).find(file.previewElement).find(".dz-image img").replaceWith('<img src="app/assets/js/dropzone/img/word-icon.png">');
        } else if (ext.indexOf("xls") != -1) {
            $(elid).find(file.previewElement).find(".dz-image img").replaceWith('<img src="app/assets/js/dropzone/img/excel-icon.png">');
        }
    });

    myDropzone.on("success", function(file, serverFileName) {
      try {
        serverFileName = JSON.parse(serverFileName);
        // console.log(serverFileName);
        file.ctrlid = serverFileName.ctrlid;
        file._url = serverFileName.file;
        file._file_type = serverFileName.file_type;
        fileList[serverFileName.ctrlid] = {"serverFileName" : serverFileName.file, "fileName" : file.name, "library_id": serverFileName.id };
      }
      catch (err) {
        console.log(err);
        console.log(serverFileName);
      }
      finally {
        
      }
    });

    myDropzone.on("removedfile", function(file) {
      var fileData = fileList[file.ctrlid];
      $.ajax({
          type: 'POST',
          url: 'app/includes/ajax.php',
          data: {"action": "remove_library_file", "serverfilename" : fileData.serverFileName, "filename" : fileData.fileName, "library_id": fileData.library_id},
          success: function(data) {
            data = JSON.parse(data);
            console.log(data);
          },
          error: function(xhr, status, error) {
          }
      });
    });
    // each instance
  });
  

});