
$(document).ready(function() {
  listFile();
}); // document.ready

let dropArea = document.getElementById('drop-area');
let filesDone = 0;
let filesToDo = 0;
let progressBar = document.getElementById('progress-bar');
let lock = 0;

$(window).on('beforeunload', function () {
  if(lock == 1) {
    return false;
  }
});

['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
  dropArea.addEventListener(eventName, preventDefaults, false)
})

function preventDefaults (e) {
  e.preventDefault()
  e.stopPropagation()
};

['dragenter', 'dragover'].forEach(eventName => {
  dropArea.addEventListener(eventName, highlight, false)
});

['dragleave', 'drop'].forEach(eventName => {
  dropArea.addEventListener(eventName, unhighlight, false)
})

function highlight(e) {
  dropArea.classList.add('highlight')
}

function unhighlight(e) {
  dropArea.classList.remove('highlight')
}

dropArea.addEventListener('drop', handleDrop, false)

function handleDrop(e) {
  let dt = e.dataTransfer
  let files = dt.files

  handleFiles(files)
}

function handleFiles(files) {
  files = [...files]
  files.forEach(uploadFile)
  files.forEach(previewFile)
}

//upload file from url
$('#url').keypress(function (e) {
  if (e.which == 13) {
    var url = encodeURIComponent($('#url').val());
    $.get({
      url: 'php/uploadUrl.php',
      data: 'url=' + url,
      beforeSend: function(){
        lock = 1;
      },
      success: function(data, statut) {
        lock = 0;
        listFile();
      },
      error: error,
    });
    return false;
  }
});

function uploadFile(file) {
  let url = 'php/upload.php'
  let formData = new FormData()

  var title = file.name;
  var startTime, endTime, fileSize, fileLoad;

  formData.append('file', file)

  $.ajax({
    xhr: function() {
      var xhr = new window.XMLHttpRequest();
      xhr.upload.addEventListener("loadstart", function(e){
        this.progressId = "progress_" + Math.floor((Math.random() * 100000));
        this.name = title;
        $("#transProgress").append('<div class="progress" id="' + this.progressId + '" ><i class="fa fa-upload"></i><span class="name"></span><progress value="0" max="100"></progress><span class="speed"></span></div>');
      });
      xhr.upload.addEventListener("progress", function(evt) {
        if (evt.lengthComputable) {
          var percentComplete = ((evt.loaded / evt.total) * 100);
          endTime = (new Date()).getTime();
          fileSize = evt.total;
          fileLoad = evt.loaded;
          var speed = fileLoad / ((endTime - startTime)/1000) / 1024 / 1024; // get speed in MB/s
          var speedMB = speed.toFixed(2) + ' MB/s ';

          $('#' + this.progressId + ' > .name').text(this.name);
          $('#' + this.progressId + ' > progress').prop('value', percentComplete);          
          $('#' + this.progressId + ' > .speed').text(speedMB + humanFileSize(fileLoad) + ' / ' + humanFileSize(fileSize));
        }
      }, false);
      return xhr;
    },
    type: 'POST',
    url: url,
    data: formData,
    contentType: false,
    cache: false,
    processData:false,
    beforeSend: function(){
      lock = 1;
      $(".progress-bar").width('0%');
      $(".progress").show();
      startTime = (new Date()).getTime();
    },
    error: error,
    success: function(data, statut){
      lock = 0;
      listFile();
    }
  });
}

function previewFile(file) {
	if (isFileImage(file)) {
		let reader = new FileReader()
		reader.readAsDataURL(file)
		reader.onloadend = function() {
			let img = document.createElement('img')
			img.src = reader.result
      img.title = file.name + " " + humanFileSize(file.size);
			document.getElementById('gallery').appendChild(img)
		}		
	}
	else {
		let span = document.createElement('span')
		span.innerHTML = file.name + " " + humanFileSize(file.size);
		document.getElementById('list').appendChild(span)
		document.getElementById('list').appendChild(document.createElement('br'))
	}
}

function listFile() {
  $.get({
    url: 'php/list.php',
    success: function(data, statut) {
      $('.list').empty();
      if (data.length > 0) {
        $('.list').append('<i class="fa fa-times delall">&ensp;Delete all files</i><br>');
      }
      $.each(data, function(key, value) {
        var encode = encodeURIComponent(value.name);
        var title = value.name + ' ' + humanFileSize(value.size);
        //$('.list').append('<a download name="' + value.name + '" class="download button ' + preview + '" href="' + value.href + '" title="' + title + '" ><i class="fa fa-' + value.type + ' type" aria-hidden="true"></i> ' + title + '</a>');
        var a = $('<a />', {
          class: 'download button',
          href: value.href.replace(value.name, encodeURIComponent(value.name)),
          name: value.name,
          title: title,
          html: '<i class="fa fa-' + value.type + ' type" aria-hidden="true"></i> ' + title
        });
        if (['file-image', 'file-video'].indexOf(value.type) > -1)
          a.addClass('preview');
        a.appendTo('.list');
        $('.list').append('<a class="fa fa-times del" href="php/delete.php?file=' + encode + '"></a><br>');
      });
      $('.preview').anarchytip();
      $('.del').click( function(event){
        var href = $(this).attr("href");
        $.get(href, listFile);
        return false; // cancel the event (don't follow link)
      });
      $('.delall').click( function(event){
        var i = 0;
        var delNB = $('.del').length;
        if(confirm("Are you sure you want to delete all files ?")) {
          $('.del').each(function(index) {
            var href = $(this).attr("href");
            $.get(href, function() {
              i++;
              if(i == delNB) //if is the last get
                listFile();
            });
          });
        }
      });
      $('.download').click(downloadFile);
    },
    error: error,
    dataType: 'json'
    });
};

function downloadFile(event) {
  var href = $(this).attr("href");
  var title = $(this).attr('name');
  var startTime, endTime, fileSize, fileLoad;
  var progressId = "progress_" + Math.floor((Math.random() * 100000));

  $.ajax({
    xhr: function() {
      var xhr = new window.XMLHttpRequest();
      xhr.addEventListener("loadstart", function(e){
        this.progressId = progressId;
        this.name = title;
        $("#transProgress").append('<div class="progress" id="' + this.progressId + '" ><i class="fa fa-download"></i><a class="name"></a><progress value="0" max="100"></progress><span class="speed"></span></div>');
      });
      xhr.addEventListener("progress", function(evt) {
        if (evt.lengthComputable) {
          var percentComplete = ((evt.loaded / evt.total) * 100);
          endTime = (new Date()).getTime();
          fileSize = evt.total;
          fileLoad = evt.loaded;
          var speed = fileLoad / ((endTime - startTime)/1000) / 1024 / 1024; // get speed in MB/s
          var speedMB = speed.toFixed(2) + ' MB/s ';

          $('#' + this.progressId + ' > .name').text(this.name);
          $('#' + this.progressId + ' > progress').prop('value', percentComplete);
          $('#' + this.progressId + ' > .speed').text(speedMB + humanFileSize(fileLoad) + ' / ' + humanFileSize(fileSize));
        }
      }, false);
      return xhr;
    },
    url: href,
    xhrFields:{
      responseType: 'blob'
    },
    beforeSend: function(){
      $(".progress-bar").width('0%');
      $(".progress").show();
      lock = 1;
      startTime = (new Date()).getTime();
    },
    success: function(data){
      lock = 0;
      var blob = data;
      var blobUrl = window.URL.createObjectURL(new Blob([blob], {type: blob.type}));
      console.log(blobUrl);
      
      $('#' + progressId + ' > .name').attr("href", blobUrl);
      $('#' + progressId + ' > .name').attr("download", title);

      var a = document.createElement("a");
      document.body.appendChild(a);
      a.style = "display: none";
      a.href = blobUrl;
      a.download = title;
      a.click();
      a.remove();
    },
    error: error,
    dataType: 'binary'
  });
  return false; // cancel the event (don't follow link)
};

function error(data, statut, error) {
  lock = 0;
  console.log(data.status + " " + data.statusText);
  console.log(data);
  //$('body').html(data['status'] + ' ' + error + '<br>' + data['responseText']);
};

function isFileImage(file) {
  return file && file['type'].split('/')[0] === 'image';
}

function humanFileSize(bytes, si=false, dp=2) {
  const thresh = si ? 1000 : 1024;

  if (Math.abs(bytes) < thresh) {
    return bytes + ' B';
  }

  const units = si 
    ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] 
    : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  let u = -1;
  const r = 10**dp;

  do {
    bytes /= thresh;
    ++u;
  } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);


  return bytes.toFixed(dp) + ' ' + units[u];
};
