# -*- encoding: utf-8 -*-

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

from crispy_forms.helper import FormHelper
from crispy_forms.layout import (HTML, ButtonHolder,
        Submit, Layout, Field, Div)

import models

class DelegationForm(ModelForm):
    username = CharField(max_length=32, label=_(u"Identifiant de l'utilisateur"))

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        self.helper = FormHelper()
        self.helper.layout = Layout(
                Div(
                    Field('username'), css_class="well"),
                ButtonHolder(HTML('<a class="btn" href=".."><i class="icon-backward"></i>Retour</a>'),
                    Submit('submit', _(u"Créer"),
                        css_class='pull-right btn-primary'),
                    css_class='well form-actions'))
        super(DelegationForm, self).__init__(*args, **kwargs)

    class Meta:
        model = models.Delegation
        fields = ()

    def clean_username(self):
        username = self.cleaned_data.get('username')
        field = models.Delegation._meta.get_field('user_delegated')
        user_model = field.related.parent_model
        try:
            user_delegated = user_model.objects.get(username=username)
        except user_model.DoesNotExist:
            raise ValidationError(_(u"Cet utilisateur n'existe pas."))
        if models.Delegation.objects.filter(user_delegating=self.user,
                user_delegated=user_delegated).exists():
            raise ValidationError(_(u"Vous avez déjà donné une délégation à cet utilisateur."))
        return user_delegated

    def clean(self):
        cleaned_data = super(DelegationForm, self).clean()
        user_delegated = cleaned_data.get('username')
        if user_delegated:
            self.instance.user_delegating = self.user
            self.instance.user_delegated = user_delegated
        return cleaned_data
