# (c) cavaliba.com - home - home.py



from .configuration_default import CONFIGURATION_DEFAULT

from app_home.models import DashboardApp



# --------------------------------------------
# Cavaliba Apps
# --------------------------------------------

def get_cavaliba_apps():

    reply = []

    appnames = [i for i in CONFIGURATION_DEFAULT]
    for appname in appnames:
        appobj = DashboardApp.objects.filter(keyname=appname).first()
        if appobj:
            reply.append(appobj)

    return reply



def get_app_by_name(appname):
    app = DashboardApp.objects.filter(keyname=appname).first()
    return app



def get_applist(aaa=None):
    '''  UI Home / Private ; filter: enabled + perm = True'''

    apps = DashboardApp.objects.all().prefetch_related("permission").order_by("order")

    reply = []

    for app in apps:

        if not app.is_enabled:
            continue

        app.is_allowed = False
        try:
            if app.permission.keyname in aaa["perms"]:
                app.is_allowed = True
        except Exception as e:
            print(e)

        reply.append(app)
    return reply


def get_sidebar(aaa=None):
    '''  CTX Processor : sidebar entries ; filter: enabled + perm = True'''

    entries = DashboardApp.objects.all().prefetch_related("permission").order_by("order")

    reply = []

    for entry in entries:

        if not entry.is_enabled:
            continue

        entry.is_allowed = False
        try:
            if entry.permission.keyname in aaa["perms"]:
                entry.is_allowed = True
        except Exception:
            pass

        reply.append(entry)

    return reply

