import { instantiate } from "./lib/rs_lib.generated.js";
const { decode_qr } = await instantiate();

function handleDragOver(evt) {
    evt.stopPropagation && evt.stopPropagation();
    evt.preventDefault && evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy';
}

function handleFileSelect(evt) {
    evt.stopPropagation && evt.stopPropagation();
    evt.preventDefault && evt.preventDefault();
    var files = evt.target.files || evt.dataTransfer.files;
    if (files.length > 1) {
        alert("Too many files!");
        return;
    }
      var f = files[0];
      if (f.size > 20 * 1024 * 1024) {
        alert("File: " + f.name + " too large: " + f.size);
        return;
      }
      console.info("N: " + f.name);
      console.info("T: " + f.type);
      console.info("S: " + f.size);
      console.info("M: " + f.lastModifiedDate);
      
      var reader = new FileReader();
      reader.onloadend = function(evt) {
        // console.info(evt);
        if (evt.target.readyState == FileReader.DONE) {
            let bs = evt.target.result;
            // debugger;
            console.log(typeof bs);
            console.log(bs);
            let qr_result = decode_qr(new Uint8Array(bs));
            console.log(qr_result);
            document.getElementById('result').innerText = JSON.stringify(JSON.parse(qr_result), null, 4);
        }
      };
      var blob = f.slice(0, f.size);
      // console.info("B: " + blob);
      reader.readAsArrayBuffer(blob);
}

var sfile = document.getElementById("sfile");
sfile.addEventListener("dragover", handleDragOver, false);
sfile.addEventListener("drop", handleFileSelect, false);
