import { Livestream } from "../lib/models.js";
import logging from '../lib/logging.js';
import { API } from '../lib/api.js';
import { knex } from "../lib/ormish.js";
import { discord, socket } from "../lib/config.js";
import { send_update_viewers, add_view_count } from "../lib/queues.js";

const log = logging.create(import.meta.url);

const next_state = (stream) => {
  if(stream.state === "pending") {
    return "ready";
  } else if(stream.state === "ready") {
    return "live";
  } else {
    return "finished";
  }
}

export const get = async (req, res) => {
  const api = new API(req, res);
  const { livestream_id } = req.query;


  try {
    if(livestream_id) {
      const stream = await Livestream.first({id: livestream_id});

      if(stream) {
        stream.media = await stream.media();
        add_view_count(livestream_id);
        api.reply(200, stream);
      } else {
        api.error(404, "not found");
      }
    } else {
      const streams = await knex(Livestream.table_name).
        orderBy("episode", "desc");

      api.reply(200, streams);
    }
  } catch (error) {
    log.error(error);
    api.error(500, error.message || "Internal Server Error");
  }
}

export const post = async (req, res) => {
  const api = new API(req, res);
  const { livestream_id } = req.body;


  try {
    if(!api.admin_authenticated) {
      return api.error(401, "Admin rights required.");
    } else if(livestream_id) {
      const stream = await Livestream.first({id: livestream_id});

      if(stream) {
        const live = next_state(stream);

        // change state to live, then the live client
        // should listen on the chat and then update the
        // UI or reload or something
        await Livestream.update({id: livestream_id}, {state: live});

        // notify connected clients that the stream has changed
        if(socket && socket.api_key) {
          send_update_viewers(socket.api_key);
        } else {
          log.error("Socket not connected or no api_key.");
        }

        return api.reply(200, {"message": "OK"});
      } else {
        return api.error(404, "not found");
      }
    } else {
      return api.error(404, "not found");
    }
  } catch (error) {
    log.error(error);
    return api.error(500, error.message || "Internal Server Error");
  }
}

post.authenticated = true;
