var messageQueue = {};

// https://stackoverflow.com/a/52171480
// simple 53-bit hash by https://github.com/bryc
const cyrb53 = function(str, seed = 0) {
  let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  for (let i = 0, ch; i < str.length; i++) {
    ch = str.charCodeAt(i);
    h1 = Math.imul(h1 ^ ch, 2654435761);
    h2 = Math.imul(h2 ^ ch, 1597334677);
  }
  h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909);
  h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909);
  return 4294967296 * (2097151 & h2) + (h1>>>0);
};

chrome.runtime.onMessage.addListener((m, n)=> {
  var nh = chrome.runtime.connectNative("org.sandpoints.chromeext")
  nh.onDisconnect.addListener((e, err)=> {
    console.log("event:", e)
    console.log("error:", err)
  })
  console.log("message:", m)
  console.log("sender:", n)
  console.log("message length:", JSON.stringify(m).length)
  const messageLength = JSON.stringify(m).length
  const digestHex = cyrb53(JSON.stringify(m)).toString();
  if (messageLength > 61440) {
    const contentLength = m.hugocontent.length
    const fragmentLength = 61440 - (messageLength - JSON.stringify(m.hugocontent).length);
    let hugocontent = ("_" + m.hugocontent).slice(1); // deep copy
    messageQueue[digestHex] = [];
    let x = 0;
    while ((x+1)*fragmentLength < contentLength+fragmentLength) {
      mm = {...m};
      mm.multipart = true;
      mm.multipartid = digestHex;
      mm.multipartnext = true;
      mm.hugocontent = hugocontent.slice(x*fragmentLength, (x+1)*fragmentLength == contentLength ? contentLength : Math.min(contentLength, (x+1)*fragmentLength))
      console.log(x*fragmentLength, (x+1)*fragmentLength, "hugocontent(start):", m.hugocontent.slice(0, 32), "hugocontent(end):", m.hugocontent.slice(m.hugocontent.length - 32))
      messageQueue[digestHex].push(mm)
      x++;
    }
    nh.postMessage(messageQueue[digestHex].shift())
  } else {
    console.log("messageLength less than 61440:", messageLength)
    m["multipart"] = false;
    m["multipartnext"] = false;
    m["multipartid"] = digestHex;
    nh.postMessage(m);
  }

  nh.onMessage.addListener((m, n)=> {
    console.log("native host message:", m)
    console.log("native host sender:", n)
    if (m.action == "redirect") {
      chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        chrome.tabs.sendMessage(tabs[0].id, { msg: m.actionid }, (response) => {
          if (response) {
            console.log(response)
          }
        });
      })
      console.log(m.actionid)
    } else if (m.action == "nextMessage") {
      if (messageQueue[m.actionid].length == 1) {
        let mm = messageQueue[m.actionid][0];
        mm.multipartnext = false;
        messageQueue[m.actionid] = [];
        nh.postMessage(mm);
      } else {
        nh.postMessage(messageQueue[m.actionid].shift())
      }
    }
  })
})


