import { writable } from 'svelte/store';

import { stop_refresh } from './common';

let refresh_interval_my = null;

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

  function updateFunc(res_my, cb=null) {
    if (res_my.status === 200) {
      res_my.json().then((my) => {
        for (let k in my.exercices) {
          my.exercices[k].id = k;

          if (my.exercices[k].flags) {
            let nb = 0;
            for (let j in my.exercices[k].flags) {
              if (!my.exercices[k].flags[j].found)
                nb += 1;
            }
            my.exercices[k].non_found_flags = nb;
          }

          if (my.team_id === 0 && my.exercices[k].hints) {
            for (let j in my.exercices[k].hints) {
              my.exercices[k].hints[j].hidden = true;
            }
          }
        }

        update((m) => (Object.assign(m?m:{}, my)));

        if (cb) {
          cb(my);
        }
      });
    } else if (res_my.status === 404) {
      update((m) => (null));
    }
  }

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

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

  return {
    subscribe,

    refresh: refreshFunc,

    update: updateFunc,
  };
}

export const my = createMyStore();
