<script>
 import SpTitle from './SpTitle.svelte'
 import SpHasTiers from './SpHasTiers.svelte'
 import SpHasWhat from './SpHasWhat.svelte'
 import SpHasCandidates from './SpHasCandidates.svelte'
 import { onMount } from 'svelte';
 let v = "loading...";
 let relpath = "";
 let relpermalink = "";
 let protocol = "";
 let title = "Foo bar";

 let hases = [];
 let frontmatter = {}
 frontmatter['triad'] = {};
 frontmatter['ascriptions'] = {};

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

 function diffArrr(arr, arrr) {
    let diff = new Set(arr)
    for (let e of arrr) {
        diff.delete(e)
    }
   return Array.from(diff)
 }

 function newHasTiers(arrgs) {
   let [fmKeyType, oldFmKey, newFmKey] = arrgs.detail;
   frontmatter[fmKeyType][oldFmKey]['candidates'] = METASP[newFmKey].tiers;
   frontmatter[fmKeyType][oldFmKey]['tiers'] = [];
 }
 
 function loadHugoPageMetadata() {
   var el = document.createElement('script');
   el.onload = ()=> {
     v = repo.content;
     if (v.startsWith("\n")) {
       v = v.substring(1)
     }

     relpath = repo.path;
     relpermalink = repo.relpermalink
     protocol = document.location.protocol.substring(0,4)
     hases = Object.keys(METASP)
     Object.entries(repo.frontmatter).forEach(([fmKey,fmValue]) =>
       {
         let fmKeyType = ''
         if (fmKey.toLowerCase().startsWith("has_")) {
           if (hases.includes(fmKey.substr(4))) {
             fmKeyType = 'triad'
             fmKey = fmKey.substr(4)
           }
         } else if (hases.includes(fmKey.toLowerCase())) {
           fmKeyType = 'ascriptions'
         }

         if (fmKeyType != "") {
           if (Array.isArray(fmValue)) {
             METASP[fmKey].tiers.forEach(t => {
               (fmKey in frontmatter[fmKeyType]) || (frontmatter[fmKeyType][fmKey] = {});
               ('tiers' in frontmatter[fmKeyType][fmKey]) || (frontmatter[fmKeyType][fmKey]['tiers'] = []);
               ('candidates' in frontmatter[fmKeyType][fmKey]) || (frontmatter[fmKeyType][fmKey]['candidates'] = []);
               if (fmValue.includes(t.file)) {
                 frontmatter[fmKeyType][fmKey]['tiers'].push(t)
               } else {
                 frontmatter[fmKeyType][fmKey]['candidates'].push(t)
               }
             })
           }
         }
       }
     )

     let tkey = Object.keys(repo.frontmatter).filter(t => t.toLowerCase() == "title")[0]
     title = repo.frontmatter[tkey]
   }
   el.src = `../js/repo/${location.hash.substring(1)}.js`
   document.body.appendChild(el)
 }
 
 function addToCandidatesRemoveFromTiers(arrgs) {
   const [tier, fmKeyType, fmKey] = arrgs.detail
   frontmatter[fmKeyType][fmKey]['tiers'] = frontmatter[fmKeyType][fmKey]['tiers'].filter(t => t !== tier);
   frontmatter[fmKeyType][fmKey]['candidates'] = [...frontmatter[fmKeyType][fmKey]['candidates'], tier]
 }

 function addToTiersRemoveFromCandidates(arrgs) {
   const [value, fmKeyType, fmKey] = arrgs.detail
   const tier = frontmatter[fmKeyType][fmKey]['candidates'].filter(t => t.file == value)
   if (tier.length > 0) {
     frontmatter[fmKeyType][fmKey]['tiers'] = [...frontmatter[fmKeyType][fmKey]['tiers'], tier[0]]
     frontmatter[fmKeyType][fmKey]['candidates'] = frontmatter[fmKeyType][fmKey]['candidates'].filter(t=> t != tier[0])
   }
 }
 
 onMount(()=> {loadHugoPageMetadata()})
</script>

<svelte:window on:keyup={keyUp}/>
<main id="sandpoints">
  <form>
    <SpTitle relpath={relpath} title={title} />
    {#each Object.entries(frontmatter) as fmItems}
      {#if ['ascriptions', 'triad'].includes(fmItems[0])}
        {#each Object.entries(fmItems[1]) as fmItem}
            <SpHasWhat fmKeyType="{fmItems[0]}" fmKey="{fmItem[0] || ''}" fmValues={fmItem[1]} hases={hases} on:hasTiersSelected={newHasTiers}  />
            <SpHasTiers on:addToCandidatesRemoveFromTiers={addToCandidatesRemoveFromTiers} fmKeyType="{fmItems[0]}" fmKey={fmItem[0] || ''} tiers={fmItem[1].tiers || []}  />
            <SpHasCandidates on:addToTiersRemoveFromCandidates={addToTiersRemoveFromCandidates} fmKeyType="{fmItems[0]}" fmKey={fmItem[0] || ''} candidates={fmItem[1].candidates || []} />
        {/each}
      {/if}
    {/each}
    <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" />
    <input type="hidden" name="relpermalink" bind:value={relpermalink} />
    <input type="hidden" name="relpath" bind:value={relpath} />
    <input type="hidden" name="protocol" bind:value={protocol} />
    <button id="sandpointsButton">COMMIT/SAVE</button>
  </form>
</main>
