from django.db.models import Case, When, IntegerField
from rest_framework import serializers

from intranet.femida.src.api.core.serializers import FemidaSerializer, WorkflowActionsField
from intranet.femida.src.api.users.serializers import UserSerializer
from intranet.femida.src.api.vacancies.serializers import VacancyListItemSerializer
from intranet.femida.src.vacancies import models
from intranet.femida.src.vacancies.choices import VACANCY_STATUSES
from intranet.femida.src.vacancies.vacancy_groups.workflow import VacancyGroupWorkflow


class VacancyGroupDetailSerializer(FemidaSerializer):

    created_by = UserSerializer()
    recruiters = UserSerializer(many=True)
    vacancies = serializers.SerializerMethodField()

    actions = WorkflowActionsField(workflow_class=VacancyGroupWorkflow)

    def get_vacancies(self, obj):
        ordering = {
            VACANCY_STATUSES.in_progress: 1,
            VACANCY_STATUSES.offer_processing: 2,
            VACANCY_STATUSES.suspended: 3,
        }

        vacancies = (
            obj.vacancies
            .annotate(status_order=Case(
                default=100,
                output_field=IntegerField(),
                *[When(status=s, then=o) for s, o in ordering.items()]
            ))
            .order_by('status_order', '-modified')
        )
        return VacancyListItemSerializer(vacancies, many=True).data

    class Meta:
        model = models.VacancyGroup
        fields = '__all__'


class VacancyGroupFormSerializer(serializers.ModelSerializer):

    created_by = serializers.CharField(source='created_by.username')
    recruiters = serializers.SerializerMethodField()

    def get_recruiters(self, obj):
        return [u.username for u in obj.recruiters.all()]

    class Meta:
        model = models.VacancyGroup
        fields = '__all__'
