# (c) cavaliba.com  - data/api - user.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_user.user import user_get_by_login
from app_user.user import user_get_by_id
from app_user.user import user_listdict_format
from app_user.user import user_search

import app_data.api.helper as helper



# permission: p_user_read

#  ----------------------------------------------------------------------------
# /api/users/
# /api/users/<id>/
# /api/users/<key>/
#  ----------------------------------------------------------------------------
@csrf_exempt
def user(request, id=None, key=None):

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

    log(DEBUG, aaa=aaa_api, app="api", view="user", action="GET", status="OK", data="")


    users = []

    # single by id
    if id:
        user = user_get_by_id(id)
        if user:
            reply = user_listdict_format([user])
            return helper.send_response(request, reply, 200)    
        else:
            return helper.send_not_found()

    # single by keyname/login
    if key:
        user = user_get_by_login(key)
        if user:
            reply = user_listdict_format([user])
            return helper.send_response(request, reply, 200)    
        else:
            return helper.send_not_found()

    
    # multi list
    search = request.GET.get('search', '')
    page = helper.get_page(request)
    size = helper.get_size(request)
    users = user_search(query=search, page=page, size=size)


    # NEXT, if expand, add group, permission, revision, related
    reply = user_listdict_format(users)
        
    if len(reply) == 0:
        return helper.send_not_found()
    # elif len(reply) == 1:
    #     return helper.send_response(request, reply[0], 200)
    else:
        return helper.send_response(request, reply, 200)

