from rest_framework import serializers

from intranet.femida.src.api.core.serializers import (
    FemidaSerializer,
    WorkflowActionsField,
    IdNameSerializer,
)
from intranet.femida.src.api.submissions.serializers import SubmissionFormSerializer
from intranet.femida.src.api.users.serializers import UserSerializer
from intranet.femida.src.candidates.challenges.workflow import ChallengeWorkflow
from intranet.femida.src.candidates.models import Challenge, Candidate, CandidateSubmission


class CandidateForChallengeSerializer(FemidaSerializer):

    extended_status = serializers.SerializerMethodField()

    def get_extended_status(self, obj):
        if 'extended_statuses' in self.root.context:
            return self.root.context['extended_statuses'].get(obj.id)

    class Meta:
        model = Candidate
        fields = (
            'id',
            'extended_status',
        )


class SubmissionForChallengeSerializer(FemidaSerializer):

    form = SubmissionFormSerializer()
    vacancies = IdNameSerializer(many=True)

    class Meta:
        model = CandidateSubmission
        fields = (
            'id',
            'publication_url',
            'form',
            'vacancies',
        )


class ChallengeBaseSerializer(FemidaSerializer):

    reviewed_by = UserSerializer()
    submission = SubmissionForChallengeSerializer()
    actions = WorkflowActionsField(ChallengeWorkflow)

    class Meta:
        model = Challenge
        fields = (
            'id',
            'type',
            'status',
            'created',
            'finished',
            'answers',
            'resolution',
            'comment',
            'formatted_comment',
            'reviewed_by',
            'submission',
            'actions',
        )


class ChallengeSerializer(ChallengeBaseSerializer):

    candidate = CandidateForChallengeSerializer()

    class Meta(ChallengeBaseSerializer.Meta):
        fields = ChallengeBaseSerializer.Meta.fields + (
            'candidate',
        )


class ChallengeEstimateFormSerializer(FemidaSerializer):

    class Meta:
        model = Challenge
        fields = (
            'resolution',
            'comment',
        )
