import { writable, derived } from 'svelte/store';

import { getQAView, getQATodo, getQAWork } from '$lib/todo';

export function createTodosStore(team) {
  const { subscribe, set, update } = writable([]);

  return {
    subscribe,

    set: (v) => {
      update((m) => Object.assign(m, v));
    },

    update,

    refresh: async () => {
      const list = await getQATodo(team);
      list.push(...await getQAWork(team));
      update((m) => list);
      return list;
    },
  };

}

export const todos = createTodosStore();

function createViewStore() {
  const { subscribe, set, update } = writable([]);

  return {
    subscribe,

    set: (v) => {
      update((m) => Object.assign(m, v));
    },

    update,

    refresh: async () => {
      const list = await getQAView();
      update((m) => list);
      return list;
    },
  };

}

export const view = createViewStore();

export const viewIdx = derived(
  view,
  $view => {
    const idx = { };

    for (const v of $view) {
      idx[v.id_exercice] = v;
    }

    return idx;
  }
);
