from datetime import datetime
from django.conf import settings
from django import template
from django.core.urlresolvers import reverse
from django.utils.dateformat import format

from newsroom.models import Story
from directory.models import Town


register = template.Library()


@register.inclusion_tag("newsroom/_story_list.html", takes_context=True)
def recent_stories(
    context, sub_stories="", count=10, town_slug="", since=datetime.now()
):
    """Inserts a list of stories, limited by the number, town and date passed.

       The returned context is a list of stories and is rendered using the _story_list.html template.
       """
    if town_slug == "":
        stories = Story.objects.get_published()
    else:
        stories = Story.objects.get_published().filter(towns__slug=town_slug)

    if not sub_stories == "":
        try:
            for s in sub_stories:
                stories = stories.exclude(id=s.id)
        except:
            stories = stories.exclude(id=sub_stories.id)

    context["stories"] = stories[0:count]
    return context


@register.inclusion_tag("newsroom/admin/inline_stories.html")
def display_stories(edition_id):
    edition = models.Edition.objects.get(id__exact=edition_id)
    stories = models.Story.objects.filter(edition_set=edition)
    return {"stories": stories}
