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

import { getTeams } from '$lib/teams'

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

  return {
    subscribe,

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

    update,

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

}

export const teams = createTeamsStore();

export const teamsIdx = derived(
  teams,
  $teams => {
    const teams_idx = { };

    for (const e of $teams) {
      teams_idx[e.id] = e;
    }

    return teams_idx;
  },
);
