/*
  Mostly just code used in the `client/pages/Live.svelte` and `client/pages/LiveIndex.svelte`
  to list and report the available livestreams.  It does some caching and normalizes how the
  streams are loaded.
 */
import api from "$/client/api.js";
import { user } from "$/client/stores.js";
import { get as get_store} from "svelte/store";

let livestreams = {};

/* Reset the cache. */
export const reset_cache = () => livestreams = {};

/* Load the available streams and cache them. */
export const load_past_streams = async () => {
  if(!livestreams.index) {
    const [status, data] = await api.get("/api/livestream");

    if(status === 200) {
      livestreams.index = data.sort((a, b) => b.id - a.id);
    } else {
      console.error("Invalid response", status, data);
    }
  }

  return livestreams.index;
}

/*
  Load a specific stream, with `cached` set to false it will bypass
  the cache when loading it.
 */
export const load_stream = async (livestream_id, cached=true) => {
  if(!cached || !livestreams[livestream_id]) {
    const [status, data] = await api.get("/api/livestream", {livestream_id});

    if(status === 200) {
      livestreams[livestream_id] = data;
    } else {
      console.error("Invalid response", status, data);
    }
  }

  return livestreams[livestream_id];
}

/*
  Changes the state of the given stream, which is an administrator only
  operation that moves it through the visual states.
 */
export const change_stream = async (livestream_id) => {
  if(get_store(user).admin) {
    const [status, data] = await api.post("/api/livestream", { livestream_id});

    return status;
  } else {
    return 401;
  }
}
