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

import { stop_refresh } from './common';

let refresh_interval_issues = null;

function createIssuesStore() {
  const { subscribe, set, update } = writable([]);

  function updateFunc (res_issues, cb=null) {
    if (res_issues.status === 200) {
      res_issues.json().then((issues) => {
        update((i) => issues);

        if (cb) {
          cb(issues);
        }
      });
    } else if (res_issues.status === 404) {
      update((i) => ([]));
    }
  }

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

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

  return {
    subscribe,

    refresh: refreshFunc,

    update: updateFunc,
  };
}

export const issuesStore = createIssuesStore();

export const issues = derived(
  issuesStore,
  ($issuesStore) => {
    $issuesStore.forEach(function(issue, k) {
      $issuesStore[k].texts.reverse();
    })
    return $issuesStore;
  },
);

export const issues_idx = derived(
  issues,
  ($issues) => {
    const issues_idx = {};

    $issues.forEach(function(issue, k) {
      issues_idx[issue.id] = issue;
    })

    return issues_idx;
  },
);

export const issues_nb_responses = derived(
  issuesStore,
  ($issuesStore) => {
    let issues_nb_responses = 0;

    $issuesStore.forEach(function(issue, k) {
      issues_nb_responses += issue.texts.length;
    })

    return issues_nb_responses;
  },
);

export const issues_need_info = derived(
  issuesStore,
  ($issuesStore) => {
    let issues_need_info = 0;

    $issuesStore.forEach(function(issue, k) {
      if (issue.state == 'need-info') issues_need_info++;
    })

    return issues_need_info;
  },
);

export const issues_known_responses = writable(0);
