# (c) cavaliba.com  - data/api - schema.py


from django.views.decorators.csrf import csrf_exempt

import app_data.api.helper as helper
from app_data.api.aaa import start_api
from app_data.models import DataInstance
from app_data.schema import Schema
from app_home.log import DEBUG, log


#  ----------------------------------------------------------------------------
# /api/schemas/
#  ----------------------------------------------------------------------------
@csrf_exempt
def schema(request, id=None, skey=None):

    aaa_api = start_api(request, permission="p_schema_read")
    if not aaa_api["is_allowed"]:
        return helper.send_denied()

    reply = {}

    # single by id
    if id:
        sc = Schema.from_id(id)
        if sc:
            reply = sc.to_dict()
            log(
                DEBUG,
                aaa=aaa_api,
                app="api",
                view="schemas",
                action="GET",
                status="OK",
                data=f"{sc.classname}",
            )
            return helper.send_response(request, [reply], 200)
        else:
            log(
                DEBUG,
                aaa=aaa_api,
                app="api",
                view="schemas",
                action="GET",
                status="KO",
                data="not found",
            )
            return helper.send_not_found()

    # single by keyname (classname)
    if skey:
        sc = Schema.from_name(skey)
        if sc:
            reply = sc.to_dict()
            log(
                DEBUG,
                aaa=aaa_api,
                app="api",
                view="schemas",
                action="GET",
                status="OK",
                data=f"{sc.classname}",
            )
            return helper.send_response(request, [reply], 200)
        else:
            log(
                DEBUG,
                aaa=aaa_api,
                app="api",
                view="schemas",
                action="GET",
                status="KO",
                data="not found",
            )
            return helper.send_not_found()

    # list all
    allobj = Schema.listall_obj()
    for sobj in allobj:
        count = DataInstance.objects.filter(classname=sobj.keyname).count()
        item = {}
        item = {
            "id": sobj.id,
            "keyname": sobj.keyname,
            "displayname": sobj.displayname,
            "is_enabled": sobj.is_enabled,
            "count": count,
        }
        reply[sobj.keyname] = item

    log(DEBUG, aaa=aaa_api, app="api", view="schemas", action="GET", status="OK", data="")
    return helper.send_response(request, reply, 200)
