from django.db.models import Count

from intranet.femida.src.api.core.pagination import JobsPagination
from intranet.femida.src.api.core.permissions import StrictServicePermission
from intranet.femida.src.api.core.views import BaseView
from intranet.femida.src.api.professions import serializers
from intranet.femida.src.professions.models import Profession
from intranet.femida.src.publications.helpers import get_publications_lang
from intranet.femida.src.publications.models import Publication


class ProfessionBaseView(BaseView):

    model_class = Profession
    authentication_classes = []
    permission_classes = [
        StrictServicePermission('permissions.can_view_external_publications'),
    ]


class ProfessionListView(ProfessionBaseView):

    pagination_class = JobsPagination
    list_item_serializer_class = serializers.ProfessionSerializer

    def get_queryset(self):
        return self.model_class.objects.filter(is_active=True)

    def get_list_item_serializer_context(self):
        lang = get_publications_lang()
        profession_ids = [p.id for p in self.page]
        publications_count_by_profession_id = dict(
            Publication.objects
            .published_external()
            .filter(
                lang=lang,
                vacancy__profession_id__in=profession_ids,
            )
            .values('vacancy__profession_id')
            .annotate(publications_count=Count('id'))
            .values_list('vacancy__profession_id', 'publications_count')
        )
        return {
            'publications_count_by_profession_id': publications_count_by_profession_id,
        }

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)


class ProfessionDetailView(ProfessionBaseView):

    detail_serializer_class = serializers.ProfessionSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)
