import { derived } from 'svelte/store';

import seedrandom from 'seedrandom';

import { my } from './my.js';
import { themes as themesStore } from './themes.js';

export const myThemes = derived([my, themesStore], ([$my, $themesStore]) => {
  const mythemes = {};

  for (let key in $themesStore) {
    mythemes[key] = {exercice_solved: 0};

    if ($my && $my.exercices) {
      for (const exercice of $themesStore[key].exercices) {
        if ($my.exercices[exercice.id] && $my.exercices[exercice.id].solved_rank) {
	  mythemes[key].exercice_solved++;
        }
      }
    }
  }

  return mythemes;
});

export const themes = derived(
  [my, themesStore],
  ([$my, $themesStore]) => {
    const arr = [];
    for (let th in $themesStore) {
      $themesStore[th].id = th
      arr.push($themesStore[th]);
    }
    const size = arr.length;
    const rng = new seedrandom($my && $my.team_id ? $my.team_id : 0);
    const respD = [];
    const respE = [];
    const keys = [];

    for(let i=0;i<size;i++) keys.push(i);
    for(let i=0;i<size;i++) {
      const r = Math.floor(rng() * keys.length);
      const g = keys[r];
      keys.splice(r,1);
      if (arr[g].locked || arr[g].exercices.length == 0 || ($my && (!$my.exercices[arr[g].exercices[0].id] || $my.exercices[arr[g].exercices[0].id].disabled))) {
        respD.push(arr[g]);
      } else {
        respE.push(arr[g]);
      }
    }

    return respE.concat(respD);
  },
);

export const tags = derived([my, themesStore], ([$my, $themesStore]) => {
  const tags = {};

  for (const key in $themesStore) {
    for (const exercice of $themesStore[key].exercices) {
      exercice.tags.forEach((tag) => {
	if (!tags[tag])
	  tags[tag] = {count: 1, solved: 0};
	else
	  tags[tag].count += 1;

        if ($my && $my.exercices && $my.exercices[exercice.id] && $my.exercices[exercice.id].solved_rank)
	  tags[tag].solved += 1;
      });
    }
  }

  return tags;
});
