# -*- coding: utf-8 -*-
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.permissions import DjangoModelPermissions
from fb.quizz.models import Quizz, QuizzQuestion, QuizzGroup, PersonAnswer
from fb.quizz.serializers import QuizzSerializer, PersonAnswerSerializer

from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import permission_required
from django.db.models import Q

from fb.staff.models import Person
from fb.staff.serializers import PersonSerializer


class QuizzList(generics.ListCreateAPIView):

    serializer_class = QuizzSerializer
    queryset = Quizz.objects.all()
    permission_classes = (DjangoModelPermissions,)

    def get_queryset(self):
        queryset = super(QuizzList, self).get_queryset()
        return (
            queryset
            .select_related('owner')
            .prefetch_related(
                'quizzgroup_set__group',
                'quizzquestion_set__quizzquestionanswer_set',
            )
        )

    def pre_save(self, obj):
        obj.owner = self.request.owner
        return super(QuizzList, self).pre_save(obj)


class UserQuizzList(generics.ListAPIView):

    serializer_class = QuizzSerializer
    queryset = Quizz.objects.all()

    def _get_quizzgroup_for_user(self, user):
        user_group_hierarchy = list(
            user.get_primary_department_hierarchy().values_list('staff_id', flat=True)
        )
        #  get suitable for user QuizzGroups
        quizzgroups = QuizzGroup.objects.filter(
            group__staff_id__in=user_group_hierarchy,
            quizz__is_published=True,
        ).filter(
            Q(include_subdepartments=True) | Q(group=user.get_primary_department().staff_id)
        ).select_related('group', 'quizz')
        #  return quizzgroup with max depth or None
        quizzgroups = quizzgroups.order_by('group__group_structure__depth')
        return quizzgroups.last()

    def get(self, request, *args, **kwargs):
        logins = request.GET.get('logins', None)
        if logins is None:
            return Response({}, status=400)
        logins = logins.split(',')
        users = Person.objects.filter(login__in=logins, is_dismissed=False).prefetch_related(
            'groupmembership_set',
            'groupmembership_set__group',
            'groupmembership_set__group__group_structure',
        )
        result = []
        for user in users:
            quizzgroup = self._get_quizzgroup_for_user(user)
            if quizzgroup is not None:
                result.append({
                    'person': PersonSerializer(instance=user).data,
                    'quiz': QuizzSerializer(instance=quizzgroup.quizz).data,
                })
            else:
                result.append({
                    'person': PersonSerializer(instance=user).data,
                    'quiz': None,
                })
        return Response(result, status=200)


class QuizzDetails(generics.RetrieveUpdateDestroyAPIView):

    serializer_class = QuizzSerializer
    queryset = Quizz.objects.all()
    lookup_field = 'id'

    @method_decorator(permission_required('quizz.change_quizz', raise_exception=True))
    def dispatch(self, request, *args, **kwargs):
        return super(QuizzDetails, self).dispatch(request, *args, **kwargs)


class PersonAnswerList(generics.ListCreateAPIView):

    serializer_class = PersonAnswerSerializer

    def pre_save(self, obj):
        obj.person = self.request.owner
        return super(PersonAnswerList, self).pre_save(obj)

    def get_queryset(self):
        staff_user = Person.objects.get(uid=self.request.yauser.uid)
        queryset = PersonAnswer.objects.filter(person=staff_user)
        return queryset


class CompetentionList(generics.ListAPIView):

    def get(self, request, *args, **kwargs):
        default_competention_names = set((
            _('competention.analytical_ability'),
            _('competention.vizionary_gaze'),
            _('competention.communication'),
            _('competention.leadership'),
            _('competention.openness'),
            _('competention.partnership'),
            _('competention.professionalism'),
            _('competention.teamwork'),
            _('competention.manage_team'),
            _('competention.management_of_conflict'),
            _('competention.resistance_to_change'),
            _('competention.efficiency'),
        ))
        issued_competention_names = set(
            QuizzQuestion.objects.filter(
                question_type=QuizzQuestion.QT_COMPETENCE
            ).values_list('text', flat=True)
        )
        competention_names = default_competention_names | issued_competention_names
        return Response(competention_names)
