# -*- 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 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
