{% extends "base.html" %}

{% block title %}Upload a SQLite database{% endblock %}

{% block extra_head %}
<style type="text/css">
#file-drop {
    border: 2px dashed #aaa;
    border-radius: 1em;
    width: 80%;
    font-family: sans-serif;
    padding: 1em;
    box-sizing: border-box;
}
#file-drop.highlight {
    border-color: purple;
    background-color: #8000801f;
}
#file-drop label {
    margin: 0;
    padding: 1em;
    font-style: italic;
    text-align: center;
    display: block;
    width: 100%;
}
input[type=file] {
    display: none;
}
progress {
    -webkit-appearance: none;
    appearance: none;
    border: none;
    width: 80%;
    height: 2em;
    margin-top: 1em;
    margin-bottom: 1em;
}
progress::-webkit-progress-bar {
    background-color: #ddd;
}
progress::-webkit-progress-value {
    background-color: #124d77;
}
</style>
{% endblock %}

{% block content %}
<h1>Upload a SQLite database</h1>

{% if error %}
  <p class="message-error">{{ error }}</p>
{% endif %}

<form action="/-/upload-dbs" id="file-form" method="post" enctype="multipart/form-data">
<div id="file-drop">
  <input type="hidden" name="csrftoken" value="{{ csrftoken() }}">
  <input type="file" name="db" id="dbUpload">
  <label for="dbUpload">Select a file to upload or drag and drop one here</label>
</div>
<p style="margin-top: 1em"><label for="id_db_name">Name:</label> <input type="text" id="id_db_name" name="db_name" size="20"></label></p>
<p><input type="submit" value="Upload database"></p>
<p style="margin-bottom: -0.8em;font-size: 0.8em; display: none;" id="progress-label">Uploading...</p>
</form>
<progress class="progress" value="0" max="100">Uploading...</progress>

<p>SQLite database files can by created using a range of different tools, including the <a href="https://sqlite-utils.datasette.io/">sqlite-utils</a> Python library and command-line utility.</p>
</ul>

<script>
const fileForm = document.getElementById("file-form");
const fileInput = document.getElementsByName("db")[0];
const dropArea = document.getElementById("file-drop");
const progress = document.getElementsByTagName("progress")[0];
const progressLabel = document.getElementById("progress-label");
const label = dropArea.getElementsByTagName("label")[0];
const nameInput = document.getElementById("id_db_name");
progress.style.display = "none";
fileForm.addEventListener("submit", (ev) => {
  ev.preventDefault();
  doUpload();
});
fileInput.addEventListener("change", () => {
  setFile(fileInput.files[0]);
});
["dragenter", "dragover", "dragleave", "drop"].forEach(eventName => {
  dropArea.addEventListener(
    eventName,
    e => {
      e.preventDefault();
      e.stopPropagation();
    },
    false
  );
});
["dragenter", "dragover"].forEach(eventName => {
  dropArea.addEventListener(
    eventName,
    () => {
      dropArea.classList.add("highlight");
    },
    false
  );
});

["dragleave", "drop"].forEach(eventName => {
  dropArea.addEventListener(
    eventName,
    () => {
      dropArea.classList.remove("highlight");
    },
    false
  );
});

dropArea.addEventListener(
  "drop",
  e => {
    setFile(e.dataTransfer.files[0]);
  },
  false
);

function formatBytes(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function setFile(file) {
  fileInput.file = file;
  label.innerText = file.name + ' - ' + formatBytes(file.size);
  if (!nameInput.value.length) {
    nameInput.value = file.name.split(".")[0];
  }
}

function doUpload() {
  var xhr = new XMLHttpRequest();
  var formData = new FormData();
  fileForm.style.display = "none";
  nameInput.closest("p").style.display = "none";
  progressLabel.style.display = "block";
  xhr.open("POST", fileInput.form.action, true);

  // Add following event listener
  xhr.upload.addEventListener("progress", function(e) {
    progress.value = (e.loaded * 100.0) / e.total || 100;
  });
  progress.style.display = "block";

  xhr.addEventListener("readystatechange", function(e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      if (/application\/json/.exec(xhr.getResponseHeader('content-type'))) {
        const data = JSON.parse(xhr.responseText);
        if (data.ok) {
          window.location = data.redirect;
        } else {
          alert(data.error);
          window.location.href = window.location.href;
        }
      } else {
        alert(xhr.responseText);
        window.location.href = window.location.href;
      }
    } else if (xhr.readyState == 4 && xhr.status != 200) {
      alert("Error!");
      window.location.href = window.location.href;
    }
  });
  formData.append("xhr", "1");
  formData.append("csrftoken", "{{ csrftoken() }}");
  formData.append("db", fileInput.file);
  xhr.send(formData);
}
</script>
{% endblock %}
