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

"""
/api/permissions/: read-only lookup of SirenePermission by id, keyname, or
paginated/searchable list.

Method inventory: permission.
"""

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.permissions import (
    permission_get_by_id,
    permission_get_by_name,
    permission_listdict_format,
    permission_search,
)
from app_home.log import DEBUG, log

# permission: p_permission_read


#  ----------------------------------------------------------------------------
# /api/permissions/
# /api/permissions/<id>/
# /api/permissions/<key>/
#  ----------------------------------------------------------------------------
@csrf_exempt
def permission(request, id=None, key=None):
    """Return a single SirenePermission by id or keyname, else a paginated/
    searchable list of all permissions."""

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

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

    # single by id
    if id:
        p = permission_get_by_id(id)
        if p:
            reply = permission_listdict_format([p])
            return helper.send_response(request, reply, 200)
        else:
            return helper.send_not_found()

    # single by keyname
    if key:
        p = permission_get_by_name(key)
        if p:
            reply = permission_listdict_format([p])
            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)
    permissions = permission_search(query=search, page=page, size=size)

    reply = permission_listdict_format(permissions)

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