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

import { getExercices } from '$lib/exercices'

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

  return {
    subscribe,

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

    update,

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

}

export const exercices = createExercicesStore();

export const exercicesIdx = derived(
  exercices,
  $exercices => {
    const exercices_idx = { };

    for (const e of $exercices) {
      exercices_idx[e.id] = e;
    }

    return exercices_idx;
  },
);

export const exercicesByTheme = derived(
  exercices,
  $exercices => {
    const exercices_idx = { };

    for (const e of $exercices) {
      if (!exercices_idx[e.id_theme]) {
        exercices_idx[e.id_theme] = []
      }
      exercices_idx[e.id_theme].push(e);
    }

    return exercices_idx;
  },
);
