<script lang="ts">
  import { query as queryFn } from "../lib/entity";
  import debounce from "lodash/debounce";
  import { Readable, readable } from "svelte/store";
  import type { UpListing } from "upend";
  import UpEntry from "../components/display/UpEntry.svelte";
  export let query: string;

  let debouncedQuery = "";
  const updateQuery = debounce((query: string) => {
    debouncedQuery = query;
  }, 200);
  $: updateQuery(query);

  let result: Readable<UpListing> = readable();
  let error: Readable<unknown> = readable();
  $: if (debouncedQuery.length) {
    ({ result, error } = queryFn(
      () => `(matches ? ? (contains "${debouncedQuery}"))`
    ));
  }
</script>

<div>
  {#if $result}
    <section>
      <h2>Objects</h2>
    </section>
    <section>
      <h2>Raw results</h2>
      <ul>
        {#each $result.entries as entry}
          <li><UpEntry {entry} /></li>
        {:else}
          <li>No results.</li>
        {/each}
      </ul>
    </section>
  {/if}
</div>

<style lang="scss">
  h2 {
    text-align: center;
  }

  ul {
    list-style: none;
    margin: 0;
  }
  
  li {
    margin: 1em auto;
    width: 66em;
  }
</style>
