import ChellarisDataStore from '$lib/stores/ChellarisData';
import SelectedGameStore from '$lib/stores/GameFilter';
import SelectedGameGroupsStore, { type SelectedChellarisGroups } from "$lib/stores/GameGroupFilter";
import GraphsTabStore from '$lib/stores/GraphsTab';
import type { LayoutLoad } from "./$types";
import type { ChellarisInfo } from '../../lib/types/chellaris';
import { apiBaseUrl } from '$lib/components/consts';

export const load: LayoutLoad = async ({ fetch }) => {
  let store: string | null;

  // Chellaris Data Code
  const chellarisData: ChellarisInfo = await (await fetch(apiBaseUrl + '/v3/full_view_data')).json();

  ChellarisDataStore.set(chellarisData);

  // Local Storage Code
  let gameGroupSelections: { [key: number]: SelectedChellarisGroups } = {};
  let gameSelection: number | undefined;

  if (typeof localStorage !== 'undefined') {
    // Tab Selection
    store = localStorage.getItem('graphsTab');
    if (typeof store === 'string') {
      GraphsTabStore.set(store);
    }

    // Game Selection
    store = localStorage.getItem('gameSelection');

    if (typeof store === 'string' && store != "\"\"") {
      gameSelection = JSON.parse(store);
    }

    if (typeof gameSelection === 'undefined') {
      gameSelection = Object.values(chellarisData.games)[0].id;
    }

    // Game Groups Selection
    store = localStorage.getItem('gameGroupSelection');

    if (typeof store === 'string') {
      gameGroupSelections = JSON.parse(store);

      if (typeof gameGroupSelections[gameSelection] === 'undefined') {
        // Default to all available groups
        gameGroupSelections[gameSelection] = { gameId: gameSelection, selectedGroups: Object.fromEntries(Object.values(chellarisData.games[gameSelection].groups).map((group) => group.id).entries()) };

        // Set Local Storage to default Values if not previously defined
        localStorage.setItem('gameGroupSelection', JSON.stringify(gameGroupSelections));
      }
      else {
        Object.keys(gameGroupSelections).forEach(
          gKey => {
            if (gameGroupSelections[+gKey] == null) {
              delete gameGroupSelections[+gKey];
            }
            else {
              Object.keys(gameGroupSelections[+gKey].selectedGroups).forEach(
                key => gameGroupSelections[+gKey].selectedGroups[+key] != null || delete gameGroupSelections[+gKey].selectedGroups[+key]
              )
            }
          });
      }
    }
  }

  if (typeof gameSelection === 'undefined') {
    gameSelection = Object.values(chellarisData.games)[0].id;
  }

  SelectedGameStore.set(gameSelection);

  if (typeof gameGroupSelections[gameSelection] === 'undefined') {
    // Default to all available groups
    gameGroupSelections[gameSelection] = { gameId: gameSelection, selectedGroups: Object.fromEntries(Object.values(chellarisData.games[gameSelection].groups).map((group) => group.id).entries()) };
  }

  SelectedGameGroupsStore.set(gameGroupSelections);

  gameGroupSelections = []; // TODO: actually assing a value
  return { chellarisData }
}