"""Mixins for Events."""
from django.http import Http404

from . import models


# Ignore PyLintBear (R0903)
class EventArchiveMixin(object):
    """Adds an is_archive = True variable to the template context."""
    context_object_name = 'event_list'
    date_field = 'start'
    make_object_list = True
    model = models.Event
    paginate_by = 15
    template_name = 'events/event_archive.html'

    def get_context_data(self, **kwargs):
        """Add is_archive to the context and set it to true.

        :return: TemplateContext object"""
        context = super(EventArchiveMixin, self).get_context_data(**kwargs)
        context['is_archive'] = True
        return context


# Ignore PyLintBear (R0903)
class EventDetailMixin(object):
    """A very simple Mixin to add the related event to the template context."""
    event = None

    def get_context_data(self, **kwargs):
        """Add self.event or the related event of self.object to the template
        context.

        :return: TemplateContext object"""
        context = super(EventDetailMixin, self).get_context_data(**kwargs)
        if hasattr(self, 'event') and self.event:
            context['event'] = self.event
        elif hasattr(self, 'object') and isinstance(self.object, models.Event):
            context['event'] = self.object
        elif hasattr(self, 'object') and hasattr(self.object, 'event'):
            context['event'] = self.object.event
        return context

    def get_queryset(self):
        """set event attribute from the URL kwarg event and
        load all related objects from the set model.

        :return: a django QuerySets
        """
        if self.model == models.Event:
            self.event = models.Event.objects.get(pk=self.kwargs['pk'])
            queryset = self.model.objects.all()
        else:
            try:
                self.event = models.Event.objects.get(pk=self.kwargs['event'])
                queryset = self.model.objects.filter(event=self.event)
            except models.Event.DoesNotExist:
                raise Http404(_('Event does not exist'))
        return queryset.prefetch_related()
