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

import { stop_refresh } from './common';

let refresh_interval_teams = null;

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

  function updateFunc(res_teams, cb=null) {
    if (res_teams.status === 200) {
      res_teams.json().then((teams) => {
        update((t) => teams);

        if (cb) {
          cb(teams);
        }
      });
    }
  }

  async function refreshFunc(cb=null, interval=null) {
    if (refresh_interval_teams)
      clearInterval(refresh_interval_teams);
    if (interval === null) {
      interval = Math.floor(Math.random() * 24000) + 32000;
    }
    if (stop_refresh.state) {
      return;
    }
    refresh_interval_teams = setInterval(refreshFunc, interval);

    updateFunc(await fetch('teams.json', {headers: {'Accept': 'application/json'}}), cb);
  }

  return {
    subscribe,

    refresh: refreshFunc,

    update: updateFunc,
  };
}

export const teamsStore = createTeamsStore();

export const teams = derived(
  teamsStore,
  ($teamsStore) => {
    const teams = {};

    for (const tid in $teamsStore) {
      teams[tid] = $teamsStore[tid];
      teams[tid].id = Number(tid);
    }

    return teams;
  }
);

export const teams_count = derived(
  teamsStore,
  ($teamsStore) => Object.keys(teams).length
);

export const rank = derived(
  teams,
  ($teams) => {
    const rank = [];

    for (const tid in $teams) {
      rank.push($teams[tid]);
    }
    rank.sort((a, b) => (a.rank > b.rank ? 1 : (a.rank == b.rank ? 0 : -1)));

    return rank;
  }
);
