function captureFrontMatterAndMarkdown() {
  const formData = new FormData(document.querySelector("form"))

  var formDataJSON = {};
  formData.forEach((value, key) => {
    if(key.endsWith('[]')){
      let kie = key.slice(0, -2);
      (kie in formDataJSON) || (formDataJSON[kie] = [])
      formDataJSON[kie].push(value);
    } else if (key.endsWith('[j]')) {
      let kie = key.slice(0, -3);
      (kie in formDataJSON) || (formDataJSON[kie] = [])
      let vA = JSON.parse(value)
      if (Array.isArray(vA)) {
        vA.forEach(v => formDataJSON[kie].push(v))
      }
    } else if (['draft', 'iscjklanguage'].includes(key) && value!="true") {
      return
    } else if (key == "relpath"){
      filepath = `${location.pathname.split('/public')[0]}/content/${value}`;
      gitpath = `${location.pathname.split('/public')[0]}`;
    } else if (key == "relpermalink" ){
      publishpath = `${location.pathname.split('/public')[0]}/public${value}index.html`;
    } else if (["protocol", "offline", "ignore"].includes(key)) {
      return
    } else if (key.startsWith("notsand")) {
      if (key.startsWith("notsandkey")) {
        let id = key.split("_")[1]
        let vA = [];
        if (formData.get(`notsandvalue_${id}`).startsWith("[")) {
          vA = JSON.parse(formData.get(`notsandvalue_${id}`))
        }
        if (Array.isArray(vA) && vA.length != 0) {
          (value in formDataJSON) || (formDataJSON[value] = [])
          vA.forEach(v => formDataJSON[value].push(v))
        } else {
          formDataJSON[value] = formData.get(`notsandvalue_${id}`)
        }
      }
    } else {
      formDataJSON[key] = value
    }
  });

  let abstract = document.getElementById('pageabstract')
  if (abstract) {
    formDataJSON['abstract'] = abstract.value
  }

  const content = document.getElementById('pagecontent').value
  let publish = formData.get("publish") == "on" ? true : false
  let offline = formData.get("offline") == "on" ? true : false
  let ret = {
    "hugofrontmatter": JSON.stringify(formDataJSON),
    "hugocontent": content,
    "filepath": filepath,
    "gitpath": gitpath,
    "publishpath": publishpath,
    "publish": publish,
    "offline": offline,
    "protocol": document.location.protocol.substr(0,4)
  }
  return ret
}

let sb = document.getElementById('sandpointsButton')
if (sb) {
  sb.addEventListener(
    "click", (e)=> {
      e.preventDefault()
      pageDict = captureFrontMatterAndMarkdown()
      chrome.runtime.sendMessage(pageDict)
  });
}

chrome.runtime.onMessage.addListener((m, n)=> {
  window.location.replace(m.msg)
})
