DEFAULT_TEMPLATE = "historical/group/default.html"
import datetime

from django.template.context import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.template import loader
from django.http import HttpResponse
from django.core.xheaders import populate_xheaders

from historical.models import *


def index(request):
    return render_to_response(
        "historical/index.html", locals(), context_instance=RequestContext(request)
    )


def group_detail(request, slug):
    object = get_object_or_404(Group, slug=slug)

    if object.template_name:
        t = loader.select_template((object.template_name, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)

    c = RequestContext(request, {"object": object,})
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Group, object.id)
    return response


def article_detail(request, group_slug, year, month, day, slug):
    object = (
        HistoricArticle.objects.published()
        .filter(group__slug=group_slug)
        .get(story__slug=slug)
    )
    return render_to_response(
        "historical/article_detail.html",
        locals(),
        context_instance=RequestContext(request),
    )


def article_archive_year(request, group_slug, year):
    objects = HistoricArticle.objects.filter(
        group__slug=group_slug, published_on__year=year
    )
    return render_to_response(
        "historical/article_archive_year.html",
        locals(),
        context_instance=RequestContext(request),
    )


def article_archive_month(request, group_slug, year, month):
    date = datetime.date(int(year), int(month), 1)
    objects = HistoricArticle.objects.filter(
        group__slug=group_slug,
        story__published_on__year=year,
        story__published_on__month=date.month,
    )
    return render_to_response(
        "historical/article_archive_month.html",
        locals(),
        context_instance=RequestContext(request),
    )


def article_archive_day(request, group_slug, year, month, day):
    date = datetime.date(int(year), int(month), int(day))
    objects = HistoricArticle.objects.filter(
        group__slug=group_slug,
        story__published_on__year=year,
        story__published_on__month=date.month,
        story__published_on__day=date.day,
    )
    return render_to_response(
        "historical/article_archive_year.html",
        locals(),
        context_instance=RequestContext(request),
    )
