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

  interface ScopeListContextData {
    scopes: Readable<Scope[]>,
    reloadScopeList(): Promise<void>,
  };

  const fallback: ScopeListContextData = {
    scopes: readable([]), 
    reloadScopeList: () => Promise.resolve()
  };

  export function getScopeListContext() {
    return getContext(contextKey) as ScopeListContextData || 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 type Scope from "$lib/models/scope";
  import { getStores } from "$app/stores";

  export let scopes: Scope[];

  const {page} = getStores();
  
  let scopesWritable = writable<Scope[]>(scopes);
  let loading = false;
  let lastSet = scopes;
  
  setContext<ScopeListContextData>(contextKey, {
    scopes: {subscribe: scopesWritable.subscribe},
    reloadScopeList,
  });

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

    try {
      const newScopes = await sl3(fetch, $page.stuff.idToken).listScopes()
      scopesWritable.set(newScopes);
    } catch(_) {}

    loading = false;
  }

  $: {
    if (lastSet !== scopes) {
      scopesWritable.set(scopes);
      lastSet = scopes;
    }
  }
</script>

<slot></slot>