import logging

from django.conf import settings
from django.db.models import Q

from staff.users.models import User
from staff.person.models import Staff

from staff.person.controllers import PersonCtl

logger = logging.getLogger('staff.person.dismissed')


def _dismissed_priveleged_users_qs():
    is_dismissed = Q(staff__is_dismissed=True)
    have_permissions = Q(
        id__in=User.user_permissions.through.objects.values_list(
            'user_id', flat=True)
    )
    is_superuser = Q(is_superuser=True)
    is_staff = Q(is_staff=True)

    result_qs = (
        User.objects.filter(
            is_dismissed & (is_superuser | is_staff | have_permissions)
        )
    )
    return result_qs


def _revoke_user_permissions(target_users):
    for user in target_users:
        user.user_permissions.clear()
        if user.is_staff or user.is_superuser:
            user.is_staff = False
            user.is_superuser = False
            user.save()
        logger.info('User %s personal permissions revoked', user)


def _delete_person_table(target_persons, author_user=None):
    for person in target_persons:
        person_ctl = PersonCtl(person)
        person_ctl.table = None
        try:
            person_ctl.save(author_user=author_user)
            logger.info('Dismissed person %s table removed', person_ctl.login)
        except Exception:
            logger.exception(
                'Error trying to update person %s while deleting it\'s table',
                person.login
            )


def revoke_dismissed_users_rights():
    target_users = _dismissed_priveleged_users_qs()
    _revoke_user_permissions(target_users)


def clear_dismissed_tables():
    target_persons = (
        Staff.objects.filter(is_dismissed=True).exclude(table_id=None)
    )
    robot_staff_user = User.objects.get(username=settings.ROBOT_STAFF_LOGIN)
    _delete_person_table(target_persons, author_user=robot_staff_user)
