{% load i18n %}
<div class="row">
  <div class="col-2">
     <form role="form" method="post" action="{{request.prefix}}/execute/launch/importfromfolder/">{% csrf_token %}

        <button type="submit" class="btn btn-primary" id="importfromfolder" value="{% trans "import"|capfirst %}">{% trans "import"|capfirst %}</button>
     </form>
  </div>
  <div class="col-10">
    <p>{% trans "Import CSV or Excel files. The file names must match the names of data objects and the first line in the file must contain the field names." %}</p>
  </div>
</div>
<div class="row mb-2 drophere">
  <div class="col-10 offset-2">
    <div class="table-responsive">
    <table class="table table-sm border-0">
    <thead>
      <tr class="border-0">
          <th class="w-100 text-nowrap border-0 align-middle px-2"><strong>{% trans 'file name'|capfirst %}</strong></th>
          <th class="text-center text-nowrap border-0 align-middle px-2"><strong>{% trans 'size'|capfirst %}</strong></th>
          <th class="text-center text-nowrap border-0 align-middle px-2"><strong><strong>{% trans 'changed'|capfirst %}</strong></strong></th>
          <th class="text-center text-nowrap border-0 align-middle px-2">
             <div class="btn btn-sm btn-primary" style="margin-bottom:5px" data-bs-toggle="tooltip"
           data-bs-placement="top" data-bs-title="{% trans "Download all files" %}"
           onClick="downloadImportFile(0)">
          <span class="fa fa-arrow-down"></span>
        </div>
        <div class="btn btn-sm btn-danger deletefile" style="margin-bottom:5px" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans 'Delete all files' %}" onClick="deleteImportFile(0, {{filestoupload}})">
          <span class="fa fa-close"></span>
        </div>
          </th>
      </tr>
    </thead>
    <tbody>
    {% for j in filestoupload %}
    <tr class="border-0" data-file="{{j.0}}">
      <td class="text-nowrap border-0 align-middle px-1">{{j.0}}</td>
      <td class="text-center text-nowrap border-0 align-middle px-2">{{j.2}}</td>
      <td class="text-nowrap text-center border-0 align-middle px-2">{{j.1}}</td>
      <td class="text-nowrap text-center border-0 align-middle px-2">
        <div class="btn btn-sm btn-primary downloadfile" style="margin-bottom:5px" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Download file" %}" onClick="downloadImportFile(0, '{{j.0}}')">
          <span class="fa fa-arrow-down"></span>
        </div>
        <div class="btn btn-sm btn-danger deletefile" style="margin-bottom:5px" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="{% trans "Delete file" %}" onClick="deleteImportFile(0, '{{j.0}}')">
          <span class="fa fa-close"></span>
        </div>
      </td>
    </tr>
    {% endfor %}
  </table>
  </div>
  </div>
</div>
    <div class="row mb-2 drophere">
    <div class="col-10 offset-2">
      <div id="addfiles2import" style="outline: 2px dashed var(--bs-body-color); outline-offset: -1em">
      <div class="text-center box__input" style="text-align: center; padding: 20px;">
      <form id="fileuploadform">
        <input class="d-none" type="file" id="fileupload" multiple />
      </form>
      <label id="fileuploadlabel" class="d-block p-3" for="fileupload">
      <a class="btn btn-primary">
        {% translate "Select files to upload" %}
      </a>&nbsp;{% translate "or drop them here" %}
      <i class="fa fa-sign-in fa-2x fa-rotate-90"></i>
      </label>
      <div id="fileuploadmsg1" class="d-none"><span></span>&nbsp;&nbsp;<i class="fa fa-spinner fa-spin"></i></div>
      <div id="fileuploadmsg2" class="d-none"><span></span>&nbsp;&nbsp;<i class="fa fa-spinner fa-spin"></i></div>
      <div id="fileuploadmsg3" class="d-none ps-3 pe-3">
        <table><tr>
          <td><i class="d-block p-3 text-danger fa fa-2x fa-exclamation-triangle"></i></td>
          <td><span></span></td>
        </tr></table>
      </div>
      </div>
      </div>
    </div>
  </div>
<script>

var filesdropped = null;
var filesselected = null;

$('.drophere')
  .on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
    e.preventDefault();
    e.stopPropagation();
  })
  .on('dragover dragenter', function () {
    $('#addfiles2import').removeClass('bg-info').addClass('bg-info');
  })
  .on('dragleave dragend drop', function () {
    $('#addfiles2import').removeClass('bg-info');
  })
  .on('drop', function (e) {
    filesdropped = e.originalEvent.dataTransfer.files;
    filesselected = null;
    if (filesdropped.length <= 0 || $("#uploadlabel").hasClass("d-none"))
      return;
    else if (filesdropped.length == 1) {
      $("#fileuploadmsg1 span").text(interpolate(gettext("Uploading file %s"), [filesdropped[0].name]));
      $("#fileuploadmsg1").toggleClass("d-none");
    }
    else {
      $("#fileuploadmsg2 span").text(interpolate(gettext("Uploading %s files"), [filesdropped.length]));
      $("#fileuploadmsg2").toggleClass("d-none");
    }
    $("#fileuploadlabel").toggleClass("d-none");
    uploadFiles();
  });

  $("#fileupload").on('change', function (e) {
    filesdropped = null;
    filesselected = e.target.files;
    if (filesselected.length <= 0 || $("#uploadlabel").hasClass("d-none"))
      return;
    else if (filesselected.length == 1) {
      $("#fileuploadmsg1 span").text(interpolate(gettext("Uploading file %s"), [filesselected[0].name]));
      $("#fileuploadmsg1").toggleClass("d-none");
    }
    else {
      $("#fileuploadmsg2 span").text(interpolate(gettext("Uploading %s files"), [filesselected.length]));
      $("#fileuploadmsg2").toggleClass("d-none");
    }
    $("#fileuploadlabel").toggleClass("d-none");
    uploadFiles();
  });

function uploadFiles() {
  filesdata = new FormData($("#fileuploadform")[0]);
  if (filesdropped) {
    $.each(filesdropped, function (i, fdropped) {
      filesdata.append(fdropped.name, fdropped);
    });
  }
  if (filesselected) {
    filesdata.delete('fileupload');
    $.each(filesselected, function (i, fdropped) {
      filesdata.append(fdropped.name, fdropped);
    });
  }

    // Upload the files
    xhr = $.ajax(
      Object.assign({
        type: 'post',
        url: '{{request.prefix}}/execute/uploadtofolder/0/',
        cache: false,
        data: filesdata,
        success: function (data) {
          $("#fileuploadlabel").removeClass("d-none");
          $("#fileuploadmsg2, #fileuploadmsg1").removeClass("d-none").addClass("d-none");
          location.reload();
        },
        error: function (result, stat, errorThrown) {
          $("#fileuploadmsg2, #fileuploadmsg1").removeClass("d-none").addClass("d-none");
          $("#fileuploadmsg3").removeClass("d-none");
          $("#fileuploadmsg3 span").html(result.responseText);
          $("#fileuploadlabel").toggleClass("d-none");
          filesdropped = null;
          filesselected = null;
        },
        processData: false,
        contentType: false
      })
    );
}

function deleteImportFile(folder, filename) {
  $.jgrid.hideModal("#searchmodfbox_grid");
  var dialogcontent;
  if (typeof filename === 'object') {
    dialogcontent = "{% trans 'You are about to delete all files' %}";
    filename = 'AllFiles';
  } else {
    dialogcontent = interpolate(gettext("You are about to delete file %s"), [filename]);
  }

  $("#popup").html('<div class="modal-dialog">'+
    '<div class="modal-content">'+
      '<div class="modal-header">'+
        '<h5 class="modal-title">{% trans 'Delete file' %}</h5>'+
        '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="' + gettext("Close") + '"></button>' +
      '</div>'+
      '<div class="modal-body"><p>'+
      dialogcontent +
      '</p></div>'+
      '<div class="modal-footer justify-content-between">'+
        '<input type="submit" id="cancelbutton" role="button" class="btn btn-primary" data-bs-dismiss="modal" value="{% trans 'Cancel' %}">'+
        '<input type="submit" id="confirmbutton" role="button" class="btn btn-danger" value="{% trans 'Confirm' %}">'+
      '</div>'+
    '</div>'+
  '</div>' );
  showModal("popup");

  $('#confirmbutton').on('click', function() {
    $.ajax({
      url: "{{request.prefix}}/execute/deletefromfolder/" + folder + "/" + filename + "/",
      type:  ("delete").toUpperCase(),
      success: function () {
        if (filename === 'AllFiles') {
          $("#popup .modal-body>p").text("{% trans 'All data files were deleted' %}");
        } else {
          $("#popup .modal-body>p").text(interpolate(gettext("File %s was deleted"), [filename]));
        }
        $('#confirmbutton').hide();
        $('#cancelbutton').attr('value', "{% trans 'Close' %}");
        $('#cancelbutton').one('click', function() {$("#popup").hide();});
        location.reload();
      },
      error: function (result, stat, errorThrown) {
        if (result.status == 401) {
          location.reload();
          return;
        }
        var filelist = result.responseText.split(' / ');
        var elem = $("#popup .modal-body>p");
        if (filelist.length === 1) {
          elem.text(interpolate(gettext("File %s was not deleted"), [filename]));
        } else {
          for (var i = 1; i < filelist.length; i++) {
            if (i === 1) {
              elem.text(interpolate(gettext("File %s was not deleted"), [filelist[i]]));
            } else {
              elem.parent().append('<p>'+interpolate(gettext("File %s was not deleted"), [filelist[i]])+'</p>');
            }
          }
        }
        $("#popup .modal-body>p").addClass('alert alert-danger');
        $('#confirmbutton').hide();
        $('#cancelbutton').attr('value', "{% trans 'Close' %}");
        $('#cancelbutton').one('click', function() {$("#popup").hide();});
        }
    })
  })
}
function downloadImportFile(folder, filename) {
  $.jgrid.hideModal("#searchmodfbox_grid");
  if (typeof filename === 'undefined')
    window.open(
      "{{request.prefix}}/execute/downloadfromfolder/" + folder + "/",
      '_blank'
      );
  else
    window.open(
      "{{request.prefix}}/execute/downloadfromfolder/" + folder + "/" + filename + '/',
      '_blank'
      );
}
</script>
