<script lang="ts">
  import {
    gameFactsStore,
    addGameFactToFactArray,
    toggleFactInFactArray,
  } from "./gameFacts";
  import type { Dialog, DialogMap, DialogSet } from "./types";
  import { findDialogSetProblems } from "./utils";

  export let currentDialog: Dialog;
  export let dialogSet: DialogSet;
  $: dialogNames = Object.keys(dialogSet.dialogs);
  export let selectedDialogName: string;

  /**
   * Collect all facts referenced in these dialogs
   */
  function getDialogFacts(dialogMap: DialogMap): String[] {
    const dialogs: Dialog[] = [];
    for (const dmKey of Object.keys(dialogMap)) dialogs.push(dialogMap[dmKey]);
    const allFacts = dialogs
      .map((dialog) => [
        ...(dialog.addFacts || []),
        ...(dialog.removeFacts || []),
        ...dialog.options.map((opt) => opt.requiredFacts).flat(),
        ...dialog.options.map((opt) => opt.forbiddenFacts).flat(),
      ])
      .flat();
    // Deduplicate entries
    const factsSet = new Set(allFacts);
    return [...factsSet].filter((e) => e !== undefined);
  }

  let seenFactIds = new Set<String>([
    ...$gameFactsStore,
    ...getDialogFacts(dialogSet.dialogs),
  ]);
  $: seenFactIdsArray = Array.from(seenFactIds);
  let addFactInputValue: string;
</script>

<div>
  <details>
      <summary>Show debug tools</summary>
      <h3>Dialog-Debugger</h3>
  Jump to dialog:
  <!-- svelte-ignore a11y-no-onchange -->
  <select
    bind:value={selectedDialogName}
    on:change={() => (currentDialog = dialogSet.dialogs[selectedDialogName])}
  >
    {#each dialogNames as dialogName}
      <option value={dialogName} selected={dialogName === selectedDialogName}>
        {dialogName}
      </option>
    {/each}
  </select>
  <br />
  <ol>
    {#each findDialogSetProblems(dialogSet) as { sourceDialog, text }}
      <li>
        {sourceDialog}: <code style="color: orange">{text}</code>
      </li>
    {/each}
  </ol>

  <hr />

  <h3>Quest-Debugger</h3>
  <b>GameFacts:</b>
  <ul>
    {#each seenFactIdsArray as gameFact}
      <li>
        <input
          type="checkbox"
          checked={$gameFactsStore.includes(gameFact)}
          on:change={() =>
            gameFactsStore.set(
              toggleFactInFactArray(gameFact, $gameFactsStore)
            )}
        />
        {gameFact}
      </li>
    {/each}
  </ul>
  Add fact:
  <input type="text" bind:value={addFactInputValue} />
  <button
    style="width: 3rem;"
    on:click={() => {
      gameFactsStore.set(
        addGameFactToFactArray(addFactInputValue, $gameFactsStore)
      );
      seenFactIds = seenFactIds.add(addFactInputValue);
      addFactInputValue = "";
    }}>Add</button
  >
  <button style="width: 13rem;" on:click={() => gameFactsStore.set([])}
    >Reset facts</button
  >
  </details>
</div>

<style>
  div {
    border: 1px solid;
    padding: 10px;
    margin: 5px;
  }
</style>