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

from django.utils.translation import ugettext_lazy as _
from django.shortcuts import redirect
from django.contrib.auth import login
from django.views.generic import TemplateView
from django.core.urlresolvers import reverse
from django.views.generic.edit import FormView, CreateView, UpdateView, DeleteView
from fiber.models import Page

import django_journal

import appli_project.appli_socle.views as socle_views
import appli_project.appli_socle.models as models
import appli_project.appli_socle.forms
from appli_project.appli_socle.utils import extraire_action_and_model
import forms

class ProfilOffreView(socle_views.SeulementPourProfil,
        socle_views.CGUCharteQualiteEtPossederMotDePasse):
    login_url = '/offre/connexion/'
    profil = (models.ProfilOffre,)

class Accueil(ProfilOffreView, TemplateView):
    template_name = 'appli_offre/accueil.html'

    def get_context_data(self, **kwargs):
        ctx = super(Accueil, self).get_context_data(**kwargs)
        annonces = models.Annonce.objects \
                .filter(proprietaire=self.request.user) \
                .order_by('-date_de_creation') \
                .prefetch_related('prestations',
                        'prestations__type_de_prestation')
        ctx['annonces'] = annonces
        ctx['annonces_publiees'] = annonces.filter(etat_validation='publiee')
        ctx['annonces_non_publiees'] = annonces.exclude(etat_validation='publiee')
        return ctx

    def post(self, request, *args, **kwargs):
        action, annonce = extraire_action_and_model(request, ('depublier', 'publier'),
                models.Annonce)
        if action == 'publier':
            annonce.publie()
            request.record('demande-publication-annonce',
                    _(u'demande la publication de l\'annonce {annonce}'),
                    annonce=annonce)
        elif action == 'depublier':
            annonce.depublie()
            request.record('depublie-annonce',
                    _(u'dépublie l\'annonce {annonce}'), annonce=annonce)
        return super(Accueil, self).get(request, *args, **kwargs)


class Connexion(socle_views.VueRelaieMixin, FormView):
    form_class = appli_project.appli_socle.forms.BaseAuthentificationForm
    template_name = 'appli_offre/connexion.html'
    static_next_url = '/offre'

    def get_form(self, form_class):
        form = super(Connexion, self).get_form(form_class)
        form.helper.form_class = 'form-inline'
        return form

    def get_form_kwargs(self):
        kwargs = super(Connexion, self).get_form_kwargs()
        kwargs['titre'] = _(u'Connexion pour les propriétaires')
        kwargs['profil'] = (models.ProfilOffre,)
        kwargs['submit_id'] = 'connexion-offre'
        kwargs['request'] = self.request
        return kwargs

    def get_success_url(self):
        return self.next_url()

    def form_valid(self, form):
        login(self.request, form.user_cache)
        self.request.record('connexion', 'connexion profil offre')
        return super(Connexion, self).form_valid(form)


class Inscription(FormView):
    form_class = forms.InscriptionForm
    template_name = 'appli_offre/inscription.html'

    def get_form_kwargs(self, **kwargs):
        kwargs = super(Inscription, self).get_form_kwargs(**kwargs)
        kwargs['request'] = self.request
        return kwargs

    def form_valid(self, form):
        form.save()
        self.request.record('preinscription', 'preinscription par '
                'l\'email {email} avec le jeton {jeton}',
                email=form.cleaned_data['email'], jeton=form.jeton)
        return super(Inscription, self).form_valid(form)

    def get_success_url(self):
        return reverse('confirmation-email', kwargs=dict(jeton=''))

class BaseAnnonceView(ProfilOffreView):
    def get_form_kwargs(self, **kwargs):
        kwargs = super(BaseAnnonceView, self).get_form_kwargs(**kwargs)
        kwargs['request'] = self.request
        return kwargs

    def get_context_data(self, **kwargs):
        ctx = super(BaseAnnonceView, self).get_context_data(**kwargs)
        ctx['annonces'] = self.get_queryset() \
                .prefetch_related('prestations',
                        'prestations__type_de_prestation')
        return ctx

    def get_queryset(self):
        return models.Annonce.objects.filter(proprietaire=self.request.user)

class NouvelleAnnonce(BaseAnnonceView, CreateView):
    template_name = 'appli_offre/nouvelle-annonce.html'
    model = models.Annonce
    form_class = forms.AnnonceForm
    success_url = '..'

    def form_valid(self, form):
        result = super(NouvelleAnnonce, self).form_valid(form)
        self.request.record('nouvelle-annonce',
                'nouvelle annonce {annonce}',
                annonce=form.instance,
                type_offre=form.instance.type_d_offre)
        form.instance.publie()
        return result

class EditerAnnonce(BaseAnnonceView, UpdateView):
    model = models.Annonce
    template_name = 'appli_offre/forms.html'
    form_class = forms.AnnonceForm

    def get_context_data(self, **kwargs):
        ctx = super(EditerAnnonce, self).get_context_data(**kwargs)
        ctx['fiber_page'] = Page.objects.get(url__exact='nouvelle-annonce')
        return ctx

    def get_success_url(self):
        return '..#annonce-%s' % self.object.id

    def form_valid(self, form):
        if 'supprimer' in self.request.POST:
            return redirect('supprimer-annonce', pk=form.instance.id)
        result = super(EditerAnnonce, self).form_valid(form)
        self.request.record('modifie-annonce',
                _(u'modifie annonce {annonce}'),
                annonce=self.object, 
                **form.cleaned_data)
        if 'modifier-et-publier' in self.request.POST:
            form.instance.publie()
            self.request.record('demande-publication-annonce',
                    _(u'modifie annonce {annonce}'),
                    annonce=self.object)
        return result

class SupprimerAnnonce(BaseAnnonceView, DeleteView):
    model = models.Annonce
    template_name = 'appli_offre/supprimer-annonce.html'
    success_url = '../..'

    def delete(self, request, *args, **kwargs):
        self.request.record('supprime-annonce',
            _(u'supprime annonce {annonce}'), annonce=self.get_object())
        return super(SupprimerAnnonce, self).delete(request, *args, **kwargs)

class MonEmail(ProfilOffreView, socle_views.VueFormulaireAvecRelaie):
    form_class = forms.MonEmailForm
    template_name = 'appli_offre/forms.html'
    success_url = '..'

    def form_valid(self, form):
        form.save()
        self.request.record('modifie-contact', 'email est "{email}" et url de contact est "{url}"',
                email=form.cleaned_data.get('email', ''),
                url=form.cleaned_data.get('url_de_contact', ''))
        return super(MonEmail, self).form_valid(form)

class MesAlertes(ProfilOffreView, socle_views.VueFormulaireAvecRelaie):
    form_class = forms.MesAlertesForm
    template_name = 'appli_offre/forms.html'

    def form_valid(self, form):
        form.save()
        self.request.record('modifie-notifications', 
            _(u'modification des options de notification'),
            **form.cleaned_data)
        return super(MesAlertes, self).form_valid(form)
