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

  interface ProjectListContextData {
    projects: Readable<ProjectEntry[]>,
    reloadProjectList(): Promise<void>,
  };

  const fallback: ProjectListContextData = {
    projects: readable([]), 
    reloadProjectList: () => Promise.resolve()
  };

  export function getProjectListContext() {
    return getContext(contextKey) as ProjectListContextData || 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 { ProjectEntry } from "$lib/models/project";
  import { getStores } from "$app/stores";

  export let projects: ProjectEntry[];

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

  let projectWritable = writable<ProjectEntry[]>(projects);
  let loading = false;
  let lastSet = projects;
  
  setContext<ProjectListContextData>(contextKey, {
    projects: {subscribe: projectWritable.subscribe},
    reloadProjectList,
  });

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

    try {
      const newProjects = await sl3(fetch, $page.stuff.idToken).listProjects($scope.id)
      projectWritable.set(newProjects);
    } catch(_) {}

    loading = false;
  }

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

<slot></slot>