import cherrypy

import config
import ovenapi


class Status:
    def _cp_dispatch(self, vpath):
        if len(vpath):
            cherrypy.request.params["vhost"] = vpath.pop(0)
        if len(vpath):
            cherrypy.request.params["app"] = vpath.pop(0)
        if len(vpath):
            cherrypy.request.params["stream"] = vpath.pop(0)

        return self

    def __init__(self):
        self.api = ovenapi.OvenAPI(config.API_USER, config.API_PASS)

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def index(self, **params: dict):
        vhost = str(params.get("vhost"))
        app = str(params.get("app"))
        # App status
        if "app" in params:
            streams = []

            # Use config.LAST_STREAM_LIST here because this is a cache of the last
            # stream list the last time the list of streams changed. It should be
            # accurate.
            for s_vhost, s_app, s_stream in config.LAST_STREAM_LIST:
                if s_vhost == vhost and s_app == app:
                    streams.append(s_stream)
            return streams

        if "vhost" not in params:
            vhost = "default"

        # Vhost status
        return self.api.get_vhost_stats(vhost)