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

  interface SprintListContextData {
    sprints: Readable<Sprint[]>,
    reloadSprintList(): Promise<void>,
  };

  const fallback: SprintListContextData = {
    sprints: readable([]), 
    reloadSprintList: () => Promise.resolve()
  };

  export function getSprintListContext() {
    return getContext(contextKey) as SprintListContextData || 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 Sprint from "$lib/models/sprint";
  import parseInterval from "$lib/utils/timeinterval";
  import { getTimeContext } from "./TimeContext.svelte";
  import { getStores } from "$app/stores";

  export let sprints: Sprint[];
  export let intervalString: string;
  export let global: boolean = false;

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

  let sprintsWritable = writable<Sprint[]>(sprints);
  let loading = false;
  let lastSet = sprints;
  
  setContext<SprintListContextData>(contextKey, {
    sprints: {subscribe: sprintsWritable.subscribe},
    reloadSprintList,
  });

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

    try {
      const newSprints = await sl3(fetch, $page.stuff.idToken).listSprints(global ? "ALL" : $scope.id, parseInterval(intervalString, $now));
      sprintsWritable.set(newSprints);
    } catch(_) {}

    loading = false;
  }

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

<slot></slot>