from django.http import HttpResponseRedirect
from django.contrib import messages
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
from django.views.generic import TemplateView

from events.models import Event


class DefaultContextMixin:
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['event'] = Event.objects.get_actual()
        if context['event']:
            context['html_sections'] = context['event'].html_sections.all().order_by('order_index')
        return context

    def dispatch(self, request, *args, **kwargs):
        try:
            event = Event.objects.get_actual()
            if not event:
                messages.error(request, _('No data found.'))
                return HttpResponseRedirect(reverse_lazy('no_data'))
        except Exception as e:
            messages.error(request, _('No data found.'))
            return HttpResponseRedirect(reverse_lazy('no_data'))
        return super().dispatch(request, *args, **kwargs)

class IndexView(DefaultContextMixin, TemplateView):
    template_name = 'core/index.html'


class NoDataView(TemplateView):
    template_name = 'core/no_data.html'

    def get(self, request, *args, **kwargs):
        data = self.get_context_data()
        return self.render_to_response(data)