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

import logging

from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.views import generic

from mtp.apps.assessments.views import RecommendationsBaseView
from mtp.apps.import_export.forms import ImportForm

from ..import_export.saba import CourseImporter

from .forms import CertificationResultsUpdateSyncStatusBulkForm

logger = logging.getLogger('mtp.custom.nissan')


class LessonReferencesImportView(RecommendationsBaseView, generic.FormView):
    """This view allows to import courses from a .csv file exported from Saba."""

    form_class = ImportForm
    template_name = 'cms/assessments/lesson_references_import.html'
    success_message = _("%(num)d lesson references were successfully imported.")
    success_url = reverse_lazy('assessments:certification-results-list')

    def form_valid(self, form):
        saba = CourseImporter(request=self.request)
        courses = saba.import_courses()

        self.send_message(data={'num': len(courses)})

        return HttpResponseRedirect(self.get_success_url())


class CertificationResultsBulkUpdateSyncStatusView(generic.FormView):
    """Base view to update multiple ``CertificationProgramUserStatus`` ``sync_status`` at once."""

    form_class = CertificationResultsUpdateSyncStatusBulkForm
    success_url = reverse_lazy('assessments:certification-results-list')

    def form_valid(self, form):
        """Update each user certification after form is valid

        For the parameters, see ``django.forms.generic.edit.FormMixin``
        """

        form.cleaned_data['certification_result'].update(
            sync_status=form.cleaned_data['sync_status'],
            sync_trigger_user=self.request.user,
        )

        messages.success(self.request, self.success_message)

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form):
        """Redirect with an error message to avoid showing the modal

        For the parameters, see ``django.forms.generic.edit.FormMixin``
        """

        logger.error(
            'UserCertificationBulkUpdateView error while validating form: %s',
            form.errors.as_data()
        )
        messages.error(self.request, _('An error occured.'))

        return HttpResponseRedirect(self.get_success_url())


class CertificationResultsBulkSkipView(CertificationResultsBulkUpdateSyncStatusView):
    """View to set ``sync_status`` to SKIP for a bunch of objects."""

    success_message = _('The user certifications were successfully marked as "treated manually".')
    template_name = 'cms/assessments/certification_results_confirm_bulk_skip.html'


class CertificationResultsBulkSendToLMSView(CertificationResultsBulkUpdateSyncStatusView):
    """View to set ``sync_status`` to QUEUED for a bunch of objects."""

    success_message = _('The user certifications were successfully scheduled to be sent to LMS.')
    template_name = 'cms/assessments/certification_results_confirm_bulk_send_to_lms.html'
