<script>
  import SpTitle from "./SpTitle.svelte";
  import SpJournal from "./SpJournal.svelte";
  import SpTiers from "./SpTiers.svelte";
  import SpKeys from "./SpKeys.svelte";
  import SpCandidates from "./SpCandidates.svelte";
  import { onMount } from "svelte";
  let v = "loading...";
  let relpath = "";
  let relpermalink = "";
  let protocol = "";
  let title = "Foo bar";
  let hases = [];
  let hasesCandidates = [];
  let frontmatter = {};
  frontmatter["triad"] = [];
  frontmatter["ascriptions"] = [];
  frontmatter["notsand"] = [];

  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, index, oldFmKey, newFmKey] = arrgs.detail;
    frontmatter[fmKeyType][index] = {
      fmKey: newFmKey,
      tiers: [],
      candidates: METASP[newFmKey].tiers,
    };
    hasesCandidates = [...hasesCandidates, oldFmKey];
    hasesCandidates = hasesCandidates.filter((h) => h != newFmKey);
  }

  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";
        } else if (["abstract", "keywords"].includes(fmKey.toLowerCase())) {
          fmKeyType = "journal";
        } else {
          fmKeyType = "notsand";
        }

        if (["triad", "ascriptions"].includes(fmKeyType)) {
          if (Array.isArray(fmValue)) {
            let tiers = [];
            let candidates = [];
            METASP[fmKey].tiers.forEach((t) => {
              if (fmValue.includes(t.file)) {
                tiers.push(t);
              } else {
                candidates.push(t);
              }
            });
            frontmatter[fmKeyType].push({
              fmKey: fmKey,
              tiers: tiers,
              candidates: candidates,
            });
          }
        } else if (fmKeyType == "journal") {
          frontmatter["journal"] || (frontmatter["journal"] = []);
          frontmatter[fmKeyType].push({ fmKey: fmKey, fmValue: JSON.stringify(fmValue) });
        }
      });
      hasesCandidates = diffArrr(hases, [
        ...frontmatter["triad"].map((t) => {
          return t.fmKey;
        }),
        ...frontmatter["ascriptions"].map((t) => {
          return t.fmKey;
        }),
      ]);

      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) {
    let [fmKeyType, index, fmKey, tier] = arrgs.detail;
    frontmatter[fmKeyType][index]["fmKey"] = fmKey;
    frontmatter[fmKeyType][index]["tiers"] = frontmatter[fmKeyType][index]["tiers"].filter(
      (t) => t !== tier
    );
    frontmatter[fmKeyType][index]["candidates"] = [...frontmatter[fmKeyType][index]["candidates"], tier];
  }

  function addToTiersRemoveFromCandidates(arrgs) {
    let [fmKeyType, index, , value] = arrgs.detail;
    const tier = frontmatter[fmKeyType][index]["candidates"].filter((t) => t.file == value);
    if (tier.length > 0) {
      frontmatter[fmKeyType][index]["tiers"] = [...frontmatter[fmKeyType][index]["tiers"], tier[0]];
      frontmatter[fmKeyType][index]["candidates"] = frontmatter[fmKeyType][index]["candidates"].filter(
        (t) => t != tier[0]
      );
    }
  }

  function toggleFold() {
    let e = document.getElementById("frontmatter");
    if (e && e.classList.contains("fmHidden")) {
      e.classList.remove("fmHidden");
      e.classList.add("fmShown");
    } else if (e && e.classList.contains("fmShown")) {
      e.classList.remove("fmShown");
      e.classList.add("fmHidden");
    }
  }

  onMount(() => {
    loadHugoPageMetadata();
    console.dir(frontmatter);
  });
</script>

<svelte:window on:keyup={keyUp} />
<main id="sandpoints">
  <form>
    <div class="formgrid">
      <SpTitle {relpath} {title} />
    </div>
    <div on:click={toggleFold} class="togglefold">[fold/unfold frontmatter]</div>
    <span id="frontmatter" class="fmHidden">
      {#each Object.entries(frontmatter) as fmItems}
        {#each fmItems[1] as fmItem, i}
          {#if ["ascriptions", "triad"].includes(fmItems[0])}
            <SpKeys
              index={i}
              fmKeyType={fmItems[0]}
              {fmItem}
              {hases}
              {hasesCandidates}
              on:hasTiersSelected={newHasTiers}
            />
            <SpTiers
              on:addToCandidatesRemoveFromTiers={addToCandidatesRemoveFromTiers}
              index={i}
              fmKeyType={fmItems[0]}
              {fmItem}
            />
            <SpCandidates
              on:addToTiersRemoveFromCandidates={addToTiersRemoveFromCandidates}
              index={i}
              fmKeyType={fmItems[0]}
              {fmItem}
            />
          {:else if fmItems[0] == "journal"}
            <label for={fmItem.fmKey}>{fmItem.fmKey}:</label>
            <input type="text" name="journal.fmKey" value={fmItem.fmValue} />
          {/if}
        {/each}
      {/each}
    </span>
    <div class="formgrid">
      <label for="content">Content:</label>
      <textarea
        bind:value={v}
        oninput="this.style.height = '';this.style.height = this.scrollHeight + 3 + 'px'"
      />
      {#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>
    </div>
  </form>
</main>
