# coding: utf-8


from django.db import models
from django.db.models import Q

from idm.core.utils import update_model


class RoleNodeSetManager(models.Manager):
    def restore_or_create(self, system, set_id, name, name_en):
        nodeset = self.filter(system=system, set_id=set_id).first()
        fields = {
            'is_active': True,
            'name': name,
            'name_en': name_en,
        }
        if nodeset is None:
            nodeset = self.create(
                system=system,
                set_id=set_id,
                **fields,
            )
        else:
            update_model(nodeset, fields)

        return nodeset

    def unlink_or_deprive_if_last(self, node):
        set_id = node.nodeset.set_id
        system = node.system
        node.nodeset = None
        node.save(update_fields=('nodeset',))
        qs = self.filter(system=system, set_id=set_id).exclude(nodes__state='active')
        qs.update(is_active=False)

    def permitted_for(self, user, node):
        """Доступные для сотрудника user группы в системе node.system ниже узла node"""
        queryset = super(RoleNodeSetManager, self).get_queryset()
        return queryset.filter(self.permitted_query(user, node))

    def permitted_query(self, user, node, **kwargs):
        from idm.core.models import Role
        roles = Role.objects.permitted_for(user, node.system).filter(system=node.system)
        roles = roles.filter(node__rolenodeclosure_parents__parent=node)
        nodeset_ids = roles.values_list('node__nodeset__id', flat=True)
        return Q(id__in=nodeset_ids, is_active=True)

    def active(self, **kwargs):
        qs = self.get_queryset().filter(is_active=True, **kwargs)
        return qs
