# (c) cavaliba.com  - data/api - asset.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.data import Instance
from app_data.search import get_instance_from_query
from app_home.log import DEBUG, log

# permission: MULTI


#  ----------------------------------------------------------------------------
# /api/assets/
# /<id>/
# /<skey>/<key>/
#  ----------------------------------------------------------------------------
@csrf_exempt
def asset(request, id=None, skey=None, key=None):

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

    search = request.GET.get("search", "")
    expand = helper.get_expand(request)
    refs = helper.get_refs(request)
    rev = helper.get_rev(request)

    log(
        DEBUG,
        aaa=aaa_api,
        app="api",
        view="asset",
        action="GET",
        status="OK",
        data=f"id={id} schema={skey} key={key} search={search}",
    )

    instance = None
    end = False

    # single by id
    if id:
        instance = Instance.from_id(id)
        end = True

    if skey and key:
        instance = Instance.from_keyname(skey, key)
        end = True

    if instance:
        if instance.has_read_permission(aaa_api):
            if expand:
                reply = instance.get_dict_for_ui_detail()
            else:
                reply = instance.get_dict_for_export(refs=refs, rev=rev)
            return helper.send_response(request, [reply], 200)
        else:
            return helper.send_denied()

    if end:
        return helper.send_not_found()

    # multi list / search
    reply = []

    page = helper.get_page(request)
    size = helper.get_size(request)
    instances = get_instance_from_query(query=search, classname=skey, page=page, size=size)

    if instances and len(instances) > 0:
        for iobj in instances:
            if expand:
                instance = Instance(iobj=iobj, expand=True)
                if instance:
                    if instance.has_read_permission(aaa_api):
                        reply.append(instance.get_dict_for_ui_detail())
            else:
                instance = Instance(iobj=iobj, expand=False)
                if instance:
                    if instance.has_read_permission(aaa_api):
                        reply.append(instance.get_dict_for_export(refs=refs))

    if len(reply) == 0:
        return helper.send_not_found()

    return helper.send_response(request, reply, 200)
