# -*- coding: utf-8 -*-

from django import forms
from django.utils.translation import ugettext_lazy as _
from django.forms.models import inlineformset_factory, BaseInlineFormSet
from django.conf import settings
from django.core.mail import EmailMultiAlternatives

from jinja2django.template.loader import render_to_string

from ..forms.fields import SplitDateTimeTimeZoneField
from ..users.models import User, Relation

from .models import Event, Topic, File, EventRelation


class EventRelationForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = EventRelation

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')

        super(EventRelationForm, self).__init__(*args, **kwargs)

        self.fields['relation'].required = False

    def clean(self):
        if not self.cleaned_data['relation']:
            try:
                mate = User.objects.get(email=self.cleaned_data['email'].lower())

            except User.DoesNotExist:
                mate = User.objects.create_user(self.cleaned_data['email'].lower())

                msg = EmailMultiAlternatives(
                    unicode(u'%s %s %s' % (_(u'Uživatel'), self.user, _(u'vás zve do systému Yes4grow'))),
                    render_to_string('users/relation_create_mail.txt', {'user': self.user, 'mate': mate}),
                    settings.DEFAULT_FROM_EMAIL,
                    [mate.email],
                )
                msg.attach_alternative(render_to_string('users/relation_create_mail.html', {'user': self.user, 'mate': mate}), 'text/html'),
                msg.send()

            if mate:
                try:
                    relation = Relation.objects.get(user=self.user, mate=mate)

                except Relation.DoesNotExist:
                    relation = Relation(user=self.user, mate=mate)

                    if self.user.pk == mate.pk:
                        relation.is_confirmed = True

                    relation.save()

                self.cleaned_data['relation'] = relation

        return super(EventRelationForm, self).clean()


class BaseEventRelationFormSet(BaseInlineFormSet):
    model = EventRelation

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')

        super(BaseEventRelationFormSet, self).__init__(*args, **kwargs)

    def _construct_form(self, i, **kwargs):
        kwargs['user'] = self.user

        return super(BaseInlineFormSet, self)._construct_form(i, **kwargs)


EventRelationFormSet = inlineformset_factory(Event, EventRelation, form=EventRelationForm, formset=BaseEventRelationFormSet, extra=0)


class EventForm(forms.ModelForm):
    term = SplitDateTimeTimeZoneField(label=_('term'))

    class Meta:
        model = Event

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')

        super(EventForm, self).__init__(*args, **kwargs)

        self.instance.user = self.user

        if self.data:
            self.eventrelation_formset = EventRelationFormSet(self.data, self.files, instance=self.instance, user=self.user)

        else:
            self.eventrelation_formset = EventRelationFormSet(instance=self.instance, user=self.user)

    def is_valid(self):
        return super(EventForm, self).is_valid() and self.eventrelation_formset.is_valid()

    def save(self, *args, **kwargs):
        instance = super(EventForm, self).save(*args, **kwargs)

        self.eventrelation_formset.save(*args, **kwargs)

        return instance


class EventFileCreateForm(forms.ModelForm):

    class Meta:
        model = File


class TopicForm(forms.ModelForm):

    class Meta:
        model = Topic


class EventSearchForm(forms.Form):
    title = forms.CharField(label=_('title'), required=False)
    date_from = forms.DateField(label=_('date from'), required=False)
    date_to = forms.DateField(label=_('date to'), required=False)
    users = forms.CharField(label=_('users / companies'), required=False)
    fulltext = forms.CharField(label=_('fulltext'), required=False)
