# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from collections import defaultdict

from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse
from django.http import response
from django.utils.translation import gettext_lazy as _
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.template import Context, Template
from django.utils.decorators import method_decorator
from django.views.generic.base import TemplateView, View
from django_yauth.decorators import yalogin_required

from app.forms import MailTemplateForm, MailTemplateEditForm
from core.models import MailTemplate
from core.tanker.api import Tanker, Keyset, Key


class ListMailTemplateView(TemplateView):

    template_name = 'mail_template_list.html'

    def get_context_data(self, **kwargs):
        context = super(ListMailTemplateView, self).get_context_data(**kwargs)
        templates_by_type = defaultdict(dict)
        templates = MailTemplate.objects.order_by('code', 'language').all()

        for template in templates:
            templates_by_type[template.code][template.language] = template

        context['templates'] = templates_by_type.items()
        return context

    @method_decorator(yalogin_required)
    @method_decorator(permission_required('core.change_mailtemplate', raise_exception=True))
    def dispatch(self, request, *args, **kwargs):
        return super(
            ListMailTemplateView,
            self,
        ).dispatch(request, *args, **kwargs)


class MailTemplateView(TemplateView):

    template_name = 'mail_template_edit.html'

    def _send_to_tanker(self, instance):
        from django.conf import settings
        t = Tanker(settings.TANKER_ID)

        prefix = settings.TANKER_PREFIX

        get_keyset = '{prefix}_{type}'.format

        keyset = Keyset(
            get_keyset(prefix=prefix, type=MailTemplate.TANKER_TYPE)
        )

        key_name = '{code}.{field}'.format

        language = instance.get_tanker_language_code()

        for field in MailTemplate.TRANSLATABLE_FIELDS:
            key = Key(key_name(code=instance.code, field=field))
            key.add_translation(
                language=language,
                form=getattr(instance, field),
            )
            keyset.add_key(key)
        t.merge_keyset(keyset, language)

    def get(self, request, template_id=None):
        instance = None
        if template_id is None:
            form = MailTemplateForm()
        else:
            instance = get_object_or_404(MailTemplate, pk=template_id)
            form = MailTemplateEditForm(instance=instance)
        return self.render_to_response(dict(
            form=form, edit=bool(instance),
            instance=instance
        ))

    def post(self, request, template_id=None):
        instance = None
        if template_id is None:
            form = MailTemplateForm(request.POST)
        else:
            instance = get_object_or_404(MailTemplate, pk=template_id)
            form = MailTemplateEditForm(request.POST, instance=instance)
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        instance = form.save()
        self._send_to_tanker(instance)
        messages.success(self.request, str(_('Page was successfully created')))
        return response.HttpResponseRedirect(reverse('mail_template:list'))

    def form_invalid(self, form):
        return self.render_to_response(dict(
            form=form, edit=True,
            instance=form.instance,
        ))

    @method_decorator(yalogin_required)
    @method_decorator(permission_required('core.change_mailtemplate', raise_exception=True))
    @method_decorator(permission_required('core.add_mailtemplate', raise_exception=True))
    def dispatch(self, request, *args, **kwargs):
        return super(MailTemplateView, self).dispatch(request, *args, **kwargs)


class DeleteMailTemplate(View):

    def post(self, request, code):
        MailTemplate.objects.filter(code=code).delete()
        return redirect('mail_template:list')

    @method_decorator(yalogin_required)
    @method_decorator(permission_required('core.delete_mailtemplate', raise_exception=True))
    def dispatch(self, request, *args, **kwargs):
        return super(
            DeleteMailTemplate,
            self,
        ).dispatch(request, *args, **kwargs)


class MailTemplatePreview(TemplateView):
    template_name = 'static_page_preview.html'

    def get(self, request, template_id):
        context = Context(request.GET)
        instance = get_object_or_404(MailTemplate, pk=template_id)
        t = Template(instance.template)
        html = t.render(context)
        return self.render_to_response(dict(html=html))

    @method_decorator(yalogin_required)
    def dispatch(self, request, *args, **kwargs):
        return super(
            MailTemplatePreview,
            self,
        ).dispatch(request, *args, **kwargs)
