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

  interface ProjectContextData {
    project: Readable<Project>,
    reloadProject(): Promise<void>,
  };

  const fallback: ProjectContextData = {
    project: readable({requirements: []} as Project),
    reloadProject: () => Promise.resolve()
  };

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

<script lang="ts">
  import type Project from "$lib/models/project";
  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 { getStores } from "$app/stores";

  export let project: Project;

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

  let projectWritable = writable<Project>(project);
  let lastSet = project;
  let loading = false;
  
  setContext<ProjectContextData>(contextKey, {
    project: {subscribe: projectWritable.subscribe},
    reloadProject,
  });

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

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

    loading = false;
  }

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

<slot></slot>