"""This module holds Nissan-specific forms for the ``assessments`` app."""

from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from mtp.apps.assessments.models.certifications import CertificationProgramUserStatus


class CertificationResultsUpdateSyncStatusBulkForm(forms.Form):
    """Form to update ``sync_status`` for a bunch of ``CertificationProgramUserStatus``"""

    cpu_queryset = CertificationProgramUserStatus.objects.filter(
        # we can only change the sync_status of certification results that
        # are at status `PENDING` or `SENT_KO`
        sync_status__in=[
            CertificationProgramUserStatus.SYNC_STATUSES.PENDING,
            CertificationProgramUserStatus.SYNC_STATUSES.SENT_KO,
        ]
    )
    certification_result = forms.ModelMultipleChoiceField(
        queryset=cpu_queryset,
        widget=forms.CheckboxSelectMultiple,
        required=False
    )

    sync_status = forms.ChoiceField(
        required=True,
        choices=CertificationProgramUserStatus.SYNC_STATUSES
    )

    def clean_certification_result(self):
        """Check that ``user`` linked to each ``certification_result`` has an ``external_id``"""

        certification_results = self.cleaned_data['certification_result']
        errors = []

        for certification_result in certification_results:
            if not certification_result.user.original_or_self_external_id:
                errors.append(ValidationError(
                    _('User %(user_id)s not linked to Saba LMS'),
                    params={'user_id': certification_result.user.pk}
                ))

        if errors:
            raise ValidationError(errors)

        return certification_results
