# vim:spell:spelllang=fr
# -*- encoding: utf-8 -*-

from django.utils.translation import ugettext_lazy as _
from django.views.generic.edit import FormView
from django.http import Http404
from django.contrib import messages

from settings import FormulaireParametres
from forms import FormulaireNotifications, InjectionProfilRechercheForm
import models

class VueParametres(FormView):
    template_name = 'admin/parametres.html'
    form_class = FormulaireParametres
    success_url = '..'

    def form_valid(self, form):
        dict_diff = form.save_form()
        self.request.logger.info(u'met à jour les paramètres')
        for key, value in dict_diff.iteritems():
            self.request.logger.info(u' - %s: %s', key, value)
        return super(VueParametres, self).form_valid(form)

class VueInjection(FormView):
    template_name = 'admin/appli_socle/profilrecherche/injection.html'
    form_class = InjectionProfilRechercheForm
    success_url = '..'

    def get_form_kwargs(self, **kwargs):
        kwargs = super(VueInjection, self).get_form_kwargs(**kwargs)
        kwargs['initial'] = {
                'type_d_offre': models.TypeOffre.objects.filter(id=1)
        }
        kwargs['request'] = self.request
        return kwargs

    def get_context_data(self, **kwargs):
        ctx = super(VueInjection, self).get_context_data(**kwargs)
        ctx['media'] = self.kwargs['media'] + ctx['form'].media
        return ctx

    def form_valid(self, form):
        count_created, count_modified = form.save()
        messages.info(self.request,
                _(u"{0} nouveaux comptes injectés, {1} comptes modifiés").format(count_created, count_modified))
        self.request.logger.info(u"%s nouveaux comptes injectés, %s comptes modifiés", count_created, count_modified)
        self.request.logger.info(u'avec les types:')
        for type_d_offre in form.cleaned_data['type_d_offre']:
            self.request.logger.info(u'- %s', type_d_offre.nom)
        self.request.logger.info(u'comptes:')
        for compte, ldap_resulat in form.cleaned_data['fichier']:
            what = u'créé' if compte in form.created else 'existant'
            self.request.logger.info(u'- %s (%s)', compte, what)
        return super(VueInjection, self).form_valid(form)

class VueNotification(FormView):
    template_name = 'admin/notifications.html'
    form_class = FormulaireNotifications
    success_url = '..'

    def dispatch(self, request, *args, **kwargs):
        if not request.user.has_perm('appli_socle.envoyer_notification'):
            raise Http404
        return super(VueNotification, self).dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        count = form.save()
        messages.info(self.request,
                _(u"{0} messages envoyés avec succès.").format(count))
        return super(VueNotification, self).form_valid(form)
