<script lang="ts" context="module">
  const contextKey = {ctx: "projectListCtx"};

  interface ItemListContextData {
    items: Readable<Item[]>,
    groups: Readable<ItemGroup[]>,
    reloadItemList(): Promise<void>,
  };

  const fallback: ItemListContextData = {
    items: readable([]),
    groups: readable([]),
    reloadItemList: () => Promise.resolve()
  };

  export function getItemListContext() {
    return getContext(contextKey) as ItemListContextData || fallback
  }
</script>

<script lang="ts">
  import { readable, writable, type Readable } from "svelte/store";
  import { getContext, setContext } from "svelte";
  import { sl3 } from "$lib/clients/sl3";
  import { getScopeContext } from "./ScopeContext.svelte";
  import type Item from "$lib/models/item";
  import type { ItemFilter, ItemGroup } from "$lib/models/item";
  import { getStores } from "$app/stores";

  export let items: Item[];
  export let groups: ItemGroup[];
  export let filter: ItemFilter;

  const {scope} = getScopeContext();
  const {page} = getStores();

  let itemsWritable = writable<Item[]>(items);
  let groupsWritable = writable<ItemGroup[]>(groups);
  let loading = false;
  let lastSet = {items, groups};
  
  setContext<ItemListContextData>(contextKey, {
    items: {subscribe: itemsWritable.subscribe},
    groups: {subscribe: groupsWritable.subscribe},
    reloadItemList,
  });

  async function reloadItemList() {
    if (loading) {
      return
    }

    try {
      const res = await sl3(fetch, $page.stuff.idToken).listItems($scope.id, filter, true, {});
      itemsWritable.set(res.items);
      groupsWritable.set(res.groups);
    } catch(_) {}

    loading = false;
  }

  $: {
    if (lastSet.items !== items || lastSet.groups !== groups) {
      itemsWritable.set(items);
      groupsWritable.set(groups);
      lastSet = {items, groups};
    }
  }
</script>

<slot></slot>