from intranet.femida.src.actionlog.decorators import action_logged
from intranet.femida.src.api.core.views import (
    unfold_query_params,
    BaseFormViewMixin,
    BaseView,
)
from intranet.femida.src.api.publications.permissions import PublicationPermission
from intranet.femida.src.api.tracker.views import TrackerTriggerBaseView
from intranet.femida.src.candidates.choices import ROTATION_STATUSES
from intranet.femida.src.candidates.models import Rotation
from intranet.femida.src.candidates.rotations.controllers import create_rotation
from intranet.femida.src.candidates.tasks import rotation_approve_task, rotation_reject_task

from . import forms, serializers


class RotationCreateView(BaseFormViewMixin, BaseView):

    model_class = Rotation
    validator_class = forms.RotationForm
    detail_serializer_class = serializers.RotationSerializer
    permission_classes = [PublicationPermission]

    @action_logged('rotation_create')
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

    def get_initial_data(self):
        return unfold_query_params(
            query_params=self.request.query_params,
            list_fields=('publications',),
        )

    def perform_create(self, data):
        return create_rotation(data, self.request.user)


class RotationTrackerTriggerBaseView(TrackerTriggerBaseView):

    model_class = Rotation
    issue_key_field = 'startrek_rotation_key'
    valid_statuses = (
        ROTATION_STATUSES.new,
    )


class RotationApproveView(RotationTrackerTriggerBaseView):

    task = rotation_approve_task


class RotationRejectView(RotationTrackerTriggerBaseView):

    task = rotation_reject_task
