import logging

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from core.decorators import log_url
from perms.models import Perm

from dashboard.models import DashboardLayout
from dashboard.widgets.widgets import FEATURES_MAP, get_widget_type_with_perms_map
from dashboard.widgets.widgets import get_widget_list_from_user
from license_info.tools import check_features

_log = logging.getLogger()


@log_url
@login_required
def dashboard(request):
    """ User's dashboard """
    # If there is no default layout for this user, create one.
    layout = DashboardLayout.objects.get_or_create(
        user=request.user
    )
    check_user_widgets(request.user)
    check_license_widgets()
    widgets_list = get_widget_list_from_user(request.user)
    form = AddWidgetForm(request.user)
    context = {'widgets': widgets_list,
               'form': form,
               'layout_id': layout[0].id}
    return render(request, 'dashboard/dashboard.html', context)


def check_user_widgets(user):
    """
    Check user perms for watching widgets

    If the user had rights to view widgets, and then they were removed, and the user already pressed these widgets,
    then after checking, the widgets will be removed from the panel."

    @param user:  A user who wants to view widgets

    """

    if user.is_superuser:
        return
    widgets = DashboardLayout.objects.get(user=user)
    if not widgets:
        return

    type_perms_map = get_widget_type_with_perms_map()
    allowed_widgets = []
    for widget in widgets.widgets:
        need_perms = type_perms_map[widget['id']]
        if all([user.has_perm(Perm.perm_req(perm)) for perm in need_perms]):
            allowed_widgets.append(widget)
    widgets.widgets = allowed_widgets
    widgets.save()


def check_license_widgets():
    """Check if we need to hide some widgets due to license restrictions"""

    dashboards = DashboardLayout.objects.all()
    for cur in dashboards:
        widgets_ids = [x['id'] for x in cur.widgets]

        for feature, bad_widgets in FEATURES_MAP.items():
            if not check_features([feature]):
                if set(bad_widgets) & set(widgets_ids):
                    allowed_widgets = [wg for wg in cur.widgets if wg["id"] not in bad_widgets]
                    cur.widgets = allowed_widgets
                    cur.save()
