# (c) cavaliba.com - app_cmt - views.py


from django.shortcuts import redirect, render

from app_cmt.common import (
    compute_daily_bargraph,
    compute_daily_ratio,
    compute_hourly_bargraph,
    compute_hourly_ratio,
    compute_live_status,
    compute_monthly_bargraph,
    compute_monthly_ratio,
    compute_quaterly_bargraph,
    compute_quaterly_ratio,
    compute_yearly_bargraph,
    compute_yearly_ratio,
    get_check,
    get_checks,
)
from app_data.aaa import start_view
from app_home.log import DEBUG, log

# -----------------------------------------------
# private - check list
# -----------------------------------------------


def list(request):
    """Dashboard: live status + hourly/daily/monthly/quaterly/yearly ratio for
    every enabled _cmtcheck."""

    context = start_view(
        request,
        app="cmt",
        view="private",
        perm="p_cmt_ui_access",
        noauthz="app_home:private",
    )

    if context["redirect"]:
        return redirect(context["redirect"])
    aaa = context["aaa"]

    checks = get_checks()

    compute_live_status(checks=checks)
    compute_hourly_ratio(checks=checks)
    compute_daily_ratio(checks=checks)
    compute_monthly_ratio(checks=checks)
    compute_quaterly_ratio(checks=checks)
    compute_yearly_ratio(checks=checks)

    checkgroups = [{"displayname": "ALL", "checks": checks}]
    context["checkgroups"] = checkgroups

    log(DEBUG, aaa=aaa, app="cmt", view="private", action="access", status="OK", data="")
    return render(request, "app_cmt/list.html", context)


# -----------------------------------------------
# detail - display check detail bargraph
# -----------------------------------------------


def detail(request, checkname=None):
    """Detail page: hourly/daily/30d/90d bargraphs for a single _cmtcheck."""

    context = start_view(
        request,
        app="cmt",
        view="detail",
        perm="p_cmt_ui_access",
        noauthz="app_home:private",
    )

    if context["redirect"]:
        return redirect(context["redirect"])
    aaa = context["aaa"]

    check = get_check(checkname)
    compute_live_status(checks=[check])

    compute_hourly_ratio(checks=[check])
    compute_hourly_bargraph(checks=[check])

    compute_daily_ratio(checks=[check])
    compute_daily_bargraph(checks=[check])

    compute_monthly_ratio(checks=[check])
    compute_monthly_bargraph(checks=[check])

    compute_quaterly_ratio(checks=[check])
    compute_quaterly_bargraph(checks=[check])

    compute_yearly_ratio(checks=[check])
    compute_yearly_bargraph(checks=[check])

    log(DEBUG, aaa=aaa, app="cmt", view="private", action="detail", status="OK", data="")

    context["check"] = check
    return render(request, "app_cmt/detail.html", context)
