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

 function disableButtons() {
   let tierbox = [...document.querySelector(".tierbox").children]
   let buttonUps = document.querySelectorAll(".buttonup")
   let buttonDowns = document.querySelectorAll(".buttondown")

   buttonUps.forEach((up)=>{
     if (tierbox.indexOf(up.parentNode) == 0) {
       up.disabled = true;
     } else {
       up.disabled = false;
     }
   })

   buttonDowns.forEach((down)=> {
     if (tierbox.indexOf(down.parentNode) == (tierbox.length -1)) {
       down.disabled = true;
     } else {
       down.disabled = false;
     }
   })
 }

 function newTierMenu() {
   let select = document.querySelector('.selecttier')
   select.innerHTML = ""
   if (couldhave.length > 0) {
     select.style.display = 'block'
     select.options[0] = new Option("Add new...", "")
     select.options[0].hidden = true
     select.options[0].selected = true
     select.options[0].disabled = true

     couldhave.forEach((c)=> {
       select.options[select.options.length] = new Option(c,c)
     })
   } else {
     select.style.display = 'none'
   }
 } 

 function addNewTier(tier, fm) {
   var tierLine = document.createElement('div')
   tierLine.classList.add('tierline')
   let removeItem = document.createElement('button')
   let moveUpItem = document.createElement('button')
   let moveDownItem = document.createElement('button')
   removeItem.setAttribute('type', 'button')
   removeItem.addEventListener('click', (e) => {
     e.target.parentNode.remove()
     couldhave.push(e.target.parentNode.querySelector("input").value)
     newTierMenu()
     disableButtons()
   })   
   removeItem.textContent = "×"

   moveUpItem.textContent = "⇑"
   moveUpItem.setAttribute('type', 'button')
   moveUpItem.classList.add('buttonup')
   moveUpItem.addEventListener('click', (e) => {
     let lb = document.querySelector(".tierbox")
     lb.insertBefore(e.currentTarget.parentNode, e.currentTarget.parentNode.previousSibling)
     disableButtons()
   })

   moveDownItem.textContent = "⇓"
   moveDownItem.setAttribute('type', 'button')
   moveDownItem.classList.add('buttondown')
   moveDownItem.addEventListener('click', (e) => {
     let lb = document.querySelector(".tierbox")
     let lblength = lb.children.length
     lb.insertBefore(e.currentTarget.parentNode, e.currentTarget.parentNode.nextSibling.nextSibling)
     disableButtons()
   })

   tierLine.prepend(moveUpItem)
   tierLine.prepend(moveDownItem)

   var input = document.createElement('input')
   input.setAttribute('type', 'text')
   input.setAttribute('name', `${fm}[]`)
   input.classList.add("hasinput")
   input.value = tier

   tierLine.prepend(input)
   tierLine.prepend(removeItem)
   return tierLine
 }

 function generateFrontMatter(frontmatter, path, relpermalink, protocol) {
   let dvm = document.querySelector('form')

   var hiddenRelPath = document.createElement('input')
   hiddenRelPath.setAttribute('type', 'hidden')
   hiddenRelPath.setAttribute('name', 'relpermalink')
   hiddenRelPath.value = relpermalink
   dvm.prepend(hiddenRelPath)
   
   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])
       
       var tierBox = document.createElement('div')
       tierBox.classList.add('tierbox')

       frontmatter[fm].reverse().forEach((tier)=>{
         tierBox.prepend(addNewTier(tier, fm))
         let removeTier = couldhave.indexOf(tier)
         if (removeTier != -1) {
           couldhave.splice(removeTier, 1)
         }
       })

       let select = document.createElement('select')
       select.addEventListener('change', (e) => {
         let tier = select.options[select.selectedIndex].value
         let i = couldhave.indexOf(tier)
         if (i != -1) {
           couldhave.splice(i, 1)
         }
         newTierMenu()
         document.querySelector('.tierbox').append(addNewTier(tier, fm))
         disableButtons()
       })
       select.classList.add('selecttier')
       dvm.prepend(select)
       newTierMenu(fm)
       dvm.prepend(tierBox)
       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)
       }
     }

     if (document.querySelector('.tierbox')) {
       console.log("What about tierbox?")
       disableButtons()
     }
   })
 }
 
 function dispatchHash() {
   var el = document.createElement('script');
   el.onload = ()=> {
     console.log("loading...")
     v = repo.content;
     if (v.startsWith("\n")) {
       v = v.substring(1)
     }
     path = repo.path;
     couldhave = METASP[Object.keys(repo.frontmatter).filter(t => t.startsWith("has_"))[0].split("has_")[1]].tiers
     console.log(JSON.stringify(repo))
     generateFrontMatter(repo.frontmatter, path, repo.relpermalink, document.location.protocol.substring(0,4))
   }
   el.src = `../js/repo/${location.hash.substring(1)}.js`
   document.body.appendChild(el) 
 }

 function keyUp(e) {
   if (e.key == "Escape") {
     window.history.back()
   }
 }

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

<svelte:window on:hashchange={hashChanged} on:keyup={keyUp}/>
<main id="sandpoints">
  <form>
    <label for="content">Content:</label>
    <textarea bind:value={v} oninput='this.style.height = "";this.style.height = this.scrollHeight + 3 + "px"'></textarea>
    {#if document.location.protocol.substring(0,4) != "file"}
      <label for="publish">Publish</label>
      <input type="checkbox" id="publish" name="publish" />
    {/if}
    <label for="offline">Offline</label>
    <input type="checkbox" id="offline" name="offline" />
    <button id="sandpointsButton">COMMIT/SAVE</button>
  </form>
</main>
