from intranet.femida.src.api.core.permissions import IsRecruiter
from intranet.femida.src.api.core.views import BaseFormViewMixin, BaseView, unfold_query_params
from intranet.femida.src.candidates.choices import CONSIDERATION_IN_PROGRESS_EXTENDED_STATUSES
from intranet.femida.src.candidates.considerations.helpers import (
    get_suitable_in_progress_considerations,
    get_suitable_archived_considerations,
)
from intranet.femida.src.candidates.models import Consideration

from . import serializers, forms


class ConsiderationDashboardListView(BaseFormViewMixin, BaseView):

    model_class = Consideration
    list_item_serializer_class = serializers.ConsiderationDashboardListSerializer
    validator_class = forms.ConsiderationDashboardListFilterForm
    permission_classes = [IsRecruiter]

    def get_queryset(self):
        return Consideration.objects.filter(candidate__is_duplicate=False)

    def filter_queryset(self, queryset):
        filter_form = self.get_validator_object(data=self.get_query_params())
        self.validate(filter_form)
        filter_params = filter_form.cleaned_data

        if filter_params['stage'] in CONSIDERATION_IN_PROGRESS_EXTENDED_STATUSES:
            queryset = get_suitable_in_progress_considerations(queryset, **filter_params)
        else:
            queryset = get_suitable_archived_considerations(queryset, **filter_params)

        return queryset.order_by('extended_status_changed_at')

    def get(self, request, *args, **kwargs):
        """
        Список рассмотрений для дашборда
        """
        return self.list(request, *args, **kwargs)

    def get_query_params(self):
        return unfold_query_params(
            query_params=self.request.query_params,
            list_fields=['users', 'professions', 'issue_types', 'vacancies'],
        )

    def get_initial_data(self):
        initial = self.get_query_params()
        if not initial.get('users'):
            initial['users'] = [self.request.user.username]
        return initial
