import api from "$/client/api.js";
import { user } from "$/client/stores.js";
import { get as get_store} from "svelte/store";

let livestreams = {};

export const reset_cache = () => livestreams = {};

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;
}

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];
}

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;
  }
}
