import sform

from django.core.exceptions import ValidationError

from intranet.femida.src.api.core.forms import (
    ProblemSuggestField,
    ConditionallyRequiredFieldsMixin,
    UserSuggestField,
    CategoryModelChoiceField,
    EMPTY_LABEL,
)
from intranet.femida.src.problems.choices import COMPLAINT_KINDS, COMPLAINT_RESOLUTIONS


class ComplaintForm(ConditionallyRequiredFieldsMixin, sform.SForm):

    problem = ProblemSuggestField(state=sform.REQUIRED)
    comment = sform.CharField()
    kind = sform.ChoiceField(choices=COMPLAINT_KINDS, state=sform.REQUIRED)
    original_problem = ProblemSuggestField()

    CONDITIONALLY_REQUIRED = {
        'original_problem': ('kind', COMPLAINT_KINDS.duplicate),
    }

    def clean(self):
        problem = self.cleaned_data.get('problem')
        original_problem = self.cleaned_data.get('original_problem')
        if problem and problem == original_problem:
            raise ValidationError(
                code='the_same_problem',
                message='Задача не может дублировать сама себя',
            )
        return self.cleaned_data


class ComplaintListFilterFrontendForm(sform.SForm):
    """
    Базовая форма, которая используется в ручке формы фильтра
    """
    moderator = UserSuggestField()
    category = CategoryModelChoiceField(empty_label=EMPTY_LABEL)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        user = self.context.get('user')
        if user:
            if user.is_moderator:
                self.fields['moderator'].default = user.username
            else:
                self.fields.pop('moderator')


class ComplaintListFilterForm(ComplaintListFilterFrontendForm):
    """
    Форма, по которой фактически происходит фильтрация списка жалоб
    """
    problem = ProblemSuggestField(skip_alive_check=True)
    original_problem = ProblemSuggestField()
    resolution = sform.ChoiceField(choices=COMPLAINT_RESOLUTIONS)
    only_active = sform.BooleanField(default=False)
