"""Django ORM Managers for the event models."""
from django.db import models
from django.utils.timezone import now


class EventManager(models.Manager):
    """Django ORM Manager that adds some queryshortcuts to Event Models."""

    def get_queryset(self):
        """Joins the location info to every event query."""
        return super(EventManager, self).get_queryset().select_related(
            'location')

    def current_event(self):
        """Returns the event that is currently running."""
        try:
            current = self.filter(start__lte=now())
            current = current.filter(end__gte=now())
            return current.order_by('start', 'end')[0]
        except IndexError:
            return None

    def next_event(self):
        """Returns the next upcoming event."""
        try:
            return self.filter(start__gt=now()).order_by('start', 'end')[0]
        except IndexError:
            return None

    def archive(self):
        """Returns all past events."""
        return self.filter(start__lt=now())

    def latest(self, limit=None):
        result = self.filter(start__lt=now()).order_by('-start', '-end')
        return result[0:limit] if limit else result

    def upcoming(self, limit=None):
        """Returns the next 'limit' upcoming events.

        :param limit: how many upcoming events should be returned?
        """
        result = self.filter(start__gt=now()).order_by('start', 'end')
        return result[0:limit] if limit else result
