import {
    ed448
} from "@noble/curves/ed448";
import {
    Buffer
} from "buffer";
var qrcode = require("qrcode");

function atoh(a) {
    return Buffer.from(a).toString("hex");
}

function htoa(h) {
  return Uint8Array.from(Buffer.from(h,"hex"));
}

function editUrl(p,u) {
  return document.location.protocol + "//" + document.location.host + "/edit.html?" + u + "#" + p;
}

export async function newItem() {
    var private_key = ed448.utils.randomPrivateKey();

    var response = await fetch("http://127.0.0.1:8000/item/prepare", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            "verification": atoh(ed448.getPublicKey(private_key))
        })
    });
    var tracking_item = await response.json();

    window.location.href = editUrl(atoh(private_key), tracking_item.uuid);
}

export async function showData(private_key, item_uuid) {
    console.log(private_key,item_uuid);
    var response = await fetch("http://127.0.0.1:8000/item/"+item_uuid);
    var tracking_item = await response.json();

    var status = document.querySelector("#status");
    if (tracking_item.deployed_at != null) {
      status.textContent = "deployed";
      status.classList.add("badge-primary");
    } else if (tracking_item.received_at != null) {
      status.textContent = "ready to deploy";
      status.classList.add("badge-success");
    } else {
      status.textContent = "waiting for delivery";
      status.classList.add("badge-warning");
    }
    qrcode.toCanvas(document.querySelector("#edit canvas"), editUrl(private_key, tracking_item.uuid));
    console.log("edit url is", editUrl(private_key, tracking_item.uuid));
    qrcode.toCanvas(document.querySelector("#receive canvas"), tracking_item.uuid + "/" + atoh(ed448.sign(new TextEncoder().encode(tracking_item.uuid), htoa(private_key))));
    console.log("receive tag is", tracking_item.uuid + "/" + atoh(ed448.sign(new TextEncoder().encode(tracking_item.uuid), htoa(private_key))));
    qrcode.toCanvas(document.querySelector("#sticker canvas"), tracking_item.uuid);
    console.log("item uuid is", tracking_item.uuid);
    document.querySelector("#sticker .tag").innerHTML = tracking_item.tag;
    console.log("item tag is", tracking_item.tag);

}