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

import json


from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt, csrf_protect

from django.utils.translation import gettext as _

from app_home.log import log, DEBUG, INFO, WARNING, ERROR, CRITICAL
from app_home.configuration import get_configuration
from app_home.cavaliba import CAVALIBA_VERSION

from app_user.aaa_api import start_api

from app_data.data import Instance
from app_data.search import get_instance_from_query


import app_data.api.helper as helper


# 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)

    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()
            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())


    if len(reply) == 0:
        return helper.send_not_found()
    
    return helper.send_response(request, reply, 200)

