# app_user - permission_views.py
# (c) cavaliba.com

from django.shortcuts import render, redirect
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 .aaa import start_view

from .permission import permission_search
from .models import SirenePermission


# ----------------------------------------------------------
# PERMISSION list
# ----------------------------------------------------------
def list(request):
    '''  display permission list'''

    context = start_view(request, app="iam", view="permission_list", noauth="app_home:index",
        perm="p_permission_read", noauthz="app_sirene:index")
    if context["redirect"]:
        return redirect(context["redirect"])
    aaa = context["aaa"]

    bigset_size = int(get_configuration("data", "DATA_BIGSET_SIZE"))
    count = SirenePermission.objects.count()
    context["count"] = count
    context["bigset"] = True

    # Search query (POST)
    query = ""
    if request.method == "POST":
        if request.POST.get('query'):
            import re
            query = request.POST.get('query')
            m = re.compile(r'[a-zA-Z0-9()_/.-]*$')
            if not m.match(query):
                query = ""
    context["query"] = query

    # Pagination (GET)
    try:
        size = int(request.GET.get("size", bigset_size))
        page = int(request.GET.get("page", 1))
    except Exception:
        return redirect("app_user:permission_list")

    if page < 1 or size > 10000 or size < 1:
        return redirect("app_user:permission_list")

    # Paginated query
    permissions = permission_search(query=query, page=page, size=size)

    log(DEBUG, aaa=aaa, app="iam", view="permission_list", action="get", status="OK", data=f"{count} permissions")

    # Pagination context
    context["size"] = size
    context["page"] = page
    page_last = int(count / size) + 1
    context["page_prev"] = max(page - 1, 1)
    context["page_first"] = (page == 1)
    context["page_current"] = (1 < page < page_last)
    context["page_last"] = page_last
    context["page_last_active"] = (page >= page_last)
    context["page_next"] = min(page + 1, page_last)

    context["permissions"] = permissions
    return render(request, 'app_user/permission_list.html', context)
