"""Mixins for Events."""
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.translation import gettext as _

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 getattr(self, 'event'):
            context['event'] = self.event
        elif isinstance(getattr(self, 'object'), models.Event):
            context['event'] = self.object
        elif getattr(getattr(self, 'object'), 'event'):
            context['event'] = self.object.event
        else:
            raise ImproperlyConfigured("No Event in Context!")
        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 = get_object_or_404(models.Event, pk=self.kwargs['pk'])
            queryset = self.model._default_manager.all()
        elif self.kwargs.get('event'):
            self.event = get_object_or_404(
                models.Event,
                pk=self.kwargs['event'])
            queryset = self.model.objects.filter(event=self.event)
        elif self.model:
            queryset = self.model._default_manager.all()
        else:
            raise ImproperlyConfigured(
                "%(cls)s is missing a QuerySet. Define "
                "%(cls)s.model, %(cls)s.queryset, or override "
                "%(cls)s.get_queryset()." % {
                    'cls': self.__class__.__name__
                })
        return queryset.prefetch_related()


class EventPhotoMixin(EventDetailMixin):

    def get_queryset(self):
        try:
            self.event = models.Event.objects.get(id=self.kwargs['event'])
            return models.Photo.objects.filter(
                Q(event=self.event) |
                Q(event__event_series=self.event)
            )
        except models.Event.DoesNotExist:
            raise Http404(_('Event does not exist'))
