let databox, progress;
function initiate() {
  databox = document.getElementById("databox");
  const button = document.getElementById("button");
  button.addEventListener("click", getdata);

  progress = document.createElement("progress");
  progress.value = 0;
  progress.max = 100;
  databox.appendChild(progress);
}
async function getdata() {
  const url = "trailer.mp4";
  try {
    const response = await fetch(url);
    if (response.ok) {
      const reader = response.body.getReader();
      const total = Number(response.headers.get("Content-Length"));
      let received = 0;
      const chunks = [];

      if (total > 0) {
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            break;
          }
          chunks.push(value);
          received += value.length;
          updatebar(received, total);
        }
        show(chunks);
      } else {
        databox.innerHTML = "No video to download.";
      }
    }
  } catch (error) {
    console.log(error);
  }
}
function updatebar(received, total) {
  const per = Math.ceil(received / total * 100);
  progress.value = per;
}
function show(chunks) {
  const blob = new Blob(chunks, { type: "video/mp4" });
  const video = URL.createObjectURL(blob);
  databox.innerHTML = '<video src="' + video + '" controls></video>';
}
window.addEventListener("DOMContentLoaded", initiate);