<script>
 import { onMount } from 'svelte';
 let v = "loading...";
 let path = "loading...";

 function generateFrontMatter(frontmatter, path, protocol) {
   let dvm = document.querySelector('form')
   var hiddenPath = document.createElement('input')
   hiddenPath.setAttribute('type', 'hidden')
   hiddenPath.setAttribute('name', 'relpath')
   hiddenPath.value = path
   dvm.prepend(hiddenPath)
   var hiddenProtocol = document.createElement('input')
   hiddenProtocol.setAttribute('type', 'hidden')
   hiddenProtocol.setAttribute('name', 'protocol')
   hiddenProtocol.value = protocol
   dvm.prepend(hiddenProtocol)
   Object.keys(frontmatter).forEach((fm)=>{
     if (Array.isArray(frontmatter[fm])) {
       console.log("Array:", frontmatter[fm])
       frontmatter[fm].forEach((i)=>{
         var input = document.createElement('input')
         input.setAttribute('type', 'text')
         input.setAttribute('name', `${fm}[]`)
         input.value = i
         dvm.prepend(input) 
       })
       let label = document.createElement('label')
       label.setAttribute('for', `${fm}[]`)
       label.innerHTML = fm + ": "
       dvm.prepend(label)
     } else {
       var input = document.createElement('input')
       console.log(fm, frontmatter[fm])
       let l = true
       if (["draft", "iscjklanguage"].includes(fm)){
         if (frontmatter[fm] == false) {
           input.setAttribute('type', 'hidden')
           l = false
         } else {
           input.setAttribute('type', 'text')   
         }
       }
       input.setAttribute('name', fm)
       input.value = frontmatter[fm]
       dvm.prepend(input)
       if (l == true) {
         let label = document.createElement('label')
         label.setAttribute('for', fm)
         label.innerHTML = fm + ": "
         dvm.prepend(label)
       }
     }
   })
 }
 
 function dispatchHash() {
   var el = document.createElement('script');
   el.onload = ()=> {
     console.log("loading...")
     v = repo.content;
     path = repo.path;
     console.log(JSON.stringify(repo))
     generateFrontMatter(repo.frontmatter, path, document.location.protocol.substring(0,4))
   }
   el.src = `../js/repo/${location.hash.substring(1)}.js`
   document.body.appendChild(el) 
 }

 onMount(()=> {
   dispatchHash()
 })
 
 $: hashChanged = ()=> dispatchHash();
</script>

<svelte:window on:hashchange={hashChanged} />
<main id="sandpoints">
  <form>
    <div class="content"><textarea>{v}</textarea></div>
    <div class="meta">Path: {path}</div>
    <label for="publish">Publish</label>
    <input type="checkbox" id="publish" name="publish" />
    <label for="offline">Offline</label>
    <input type="checkbox" id="offline" name="offline" />
    <div class="btns"><button id="sandpointsButton">BANG</button></div>
  </form>
</main>
