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

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

  return {
    subscribe,

    refresh: async (cb) => {
      challengeInfo.update(await fetch('challenge.json', {headers: {'Accept': 'application/json'}}), cb);
    },

    update: (res_challenge, cb) => {
      if (res_challenge.status === 200) {
        res_challenge.json().then((challenge) => {
          update((s) => (Object.assign({}, challenge)));

          if (cb) {
            cb(challenge);
          }
        });
      }
    },
  }
}

export const challengeInfo = createChallengeStore();
