# -*- coding: utf-8 -*-
from aldryn_search.views import AldrynSearchView
from cms.models import Page
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from django.views.generic.edit import FormView
from aldryn_forms.admin.views import FormExportWizardView
from aldryn_forms.admin.exporter import Exporter
from tablib import Dataset
from django.http import HttpResponse
from project.forms import NewsletterSubscriptionForm


class SearchView(AldrynSearchView):
    template_name = 'project/search.html'
    context_object_name = 'search_results'

    def get_context_data(self, **kwargs):
        context = super(SearchView, self).get_context_data(**kwargs)
        search_form = context['form']
        context['search_form'] = search_form
        del context['form']
        return context


class NewsletterSubscriptionView(FormView):
    template_name = 'project/newsletter/subscription.html'
    form_class = NewsletterSubscriptionForm
    success_url = reverse_lazy('newsletter_subscription_success')


class LoginRedirectView(RedirectView):

    def get_redirect_url(self, *args, **kwargs):
        fallback_url = '/'
        try:
            portal_page = Page.objects.public().get(reverse_id='portal')
            portal_url = portal_page.get_public_url()
            if portal_url:
                return portal_url
            else:
                return fallback_url
        except Page.DoesNotExist:
            return fallback_url


class MediaRedirectView(RedirectView):

    def get_redirect_url(self, *args, **kwargs):
        return self.request.GET.get('url', None)


class CustomExporter(Exporter):
    custom_fields = ['sent_at']

    def get_dataset(self, fields):
        headers = [field.rpartition('-')[0] for field in fields]

        for custom_field in self.custom_fields:
            headers.append(custom_field)

        dataset = Dataset(headers=headers)

        for submission in self.queryset.only('data').iterator():
            row_data = []
            form_fields = [field for field in submission.get_form_data()
                           if field.field_id in fields]

            for header in fields:
                for field in form_fields:
                    if field.field_id == header:
                        row_data.append(field.value)
                        break
                else:
                    row_data.append('')

            if row_data:
                for custom_field in self.custom_fields:
                    row_data.append(getattr(submission, custom_field).strftime('%d.%m.%Y %H:%M:%S'))
                dataset.append(row_data)
        return dataset


class CustomFormExportWizardView(FormExportWizardView):
    
    def done(self, form_list, **kwargs):
        """
        this step only runs if all forms are valid.
        """
        form_iter = iter(form_list)
        step_1_form = next(form_iter)
        step_2_form = next(form_iter)

        fields = step_2_form.get_fields()
        queryset = step_1_form.get_queryset()

        dataset = CustomExporter(queryset=queryset).get_dataset(fields=fields)

        filename = step_1_form.get_filename(extension=self.file_type)

        content_type = self.get_content_type()
        response = HttpResponse(dataset.xls, content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response
