import sform

from staff.preprofile.action_context import ActionContext
from staff.preprofile.forms.fields import ticket_fields, official_fields
from staff.preprofile.forms.validation import validate_login_with_candidate_type


class FemidaEditForm(sform.SForm):
    hr_ticket = ticket_fields.hr_ticket(required=False)
    adopt_ticket = ticket_fields.adopt_ticket(required=False)

    join_at = official_fields.join_at(required=False)
    login = official_fields.human_login()
    candidate_type = official_fields.candidate_type()
    department = official_fields.department()
    date_completion_internship = official_fields.date_completion_internship(readonly=False)

    @property
    def action_context(self) -> ActionContext:
        return self.base_initial['action_context']

    def clean(self):
        cleaned_data = self.cleaned_data
        preprofile = self.action_context.preprofile

        # Не принимать логин из формы, если уже присвоен uid/guid
        if preprofile.has_uid_or_guid:
            cleaned_data['login'] = preprofile.login

        login_related_fields = ['login', 'candidate_type']
        if any([field not in cleaned_data for field in login_related_fields]):
            return {}
        login = cleaned_data['login']
        candidate_type = cleaned_data['candidate_type']
        # Валидируем, только если что-то изменилось
        if any(getattr(preprofile, f) != cleaned_data[f] for f in login_related_fields):
            validate_login_with_candidate_type(login, candidate_type, preprofile.id)

        return super(FemidaEditForm, self).clean()
