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



from django.views.decorators.csrf import csrf_exempt


from app_home.log import log, DEBUG

from app_user.aaa_api import start_api


from app_user.group import group_get_by_name
from app_user.group import group_get_by_id
from app_user.group import group_listdict_format
from app_user.group import group_search

import app_data.api.helper as helper



# permission: p_group_read

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

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

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


    # single by id
    if id:
        grp = group_get_by_id(id)
        if grp:
            reply = group_listdict_format([grp])
            return helper.send_response(request, reply, 200)
        else:
            return helper.send_not_found()

    # single by keyname/name
    if key:
        grp = group_get_by_name(key)
        if grp:
            reply = group_listdict_format([grp])
            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)
    groups = group_search(query=search, page=page, size=size)

    reply = group_listdict_format(groups)

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