import sha256 from "sha256-wasm";

export function searchHashPage() {
  const FORM = document.getElementById("file-search");
  const FILE = document.getElementById("file");
  const HASH = document.getElementById("hash");

  FORM.addEventListener("submit", async function (e) {

    e.preventDefault();
    let hash = undefined;
    if (FILE.value !== "") {
      hash = await getFileHash(FILE.files[0]);
    } else if (HASH.value !== "") {
      if (HASH.value.match(/[A-Fa-f0-9]{64}/)) {
        hash = HASH.value;
      } else {
        alert("Invalid SHA256 hash");
      }
    } else {
      alert("Neither file or hash provided");
    }

    if (hash) {
      window.location.search = "?hash=" + hash;
    }
  });
}

async function getFileHash(file) {
  const fileSize = file.size;
  const chunkSize = 1024 * 1024; // 1Mi
  let offset = 0;
  let hash = new sha256();

  while (offset < fileSize) {
    const arr = new Uint8Array(await file.slice(offset, chunkSize + offset).arrayBuffer());
    hash.update(arr);
    offset += chunkSize;
  }

  return hash.digest("hex");
}
