from django.shortcuts import get_object_or_404, render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.template import loader, RequestContext
import datetime, time


def archive_monthdays(request, year, month, queryset, date_field,
        month_format='%b', template_name=None, template_loader=loader,
        extra_context=None, allow_empty=False, context_processors=None,
        template_object_name='object', mimetype=None, make_object_list=False, allow_future=False):
    """
    Generic monthly archive view, broken down by date.

    Templates: ``<app_label>/<model_name>_archive_monthdays.html``
    Context:
        month:
            (date) this month
        next_month:
            (date) the first day of the next month, or None if the next month is in the future
        previous_month:
            (date) the first day of the previous month
        year:
            (str) the year
        days:
           (dates)  days in this month
        object_list
            List of objects published in the given month
            (Only available if make_object_list argument is True)

    Example use:

{% extends "base_site.html" %}

{% block content %}
	&lt;h2>{{ month|date:"F" }} {{ year }} Archive&lt;/h2>
	
&lt;ul class="linklist">
	{% for date in days %}
		&lt;li>
          &lt;a href="{{ date|date:"d"|lower }}/">
             {{ date|date:"D" }} {{ date|date:"d" }}&lt;/a>
        &lt;/li>
	{% endfor %}
&lt;/ul>

{% endblock %}

    """
    if extra_context is None: extra_context = {}
    try:
        date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3])
    except ValueError:
        raise Http404

    model = queryset.model
    now = datetime.datetime.now()

    # Calculate first and last day of month, for use in a date-range lookup.
    first_day = date.replace(day=1)
    if first_day.month == 12:
        last_day = first_day.replace(year=first_day.year + 1, month=1)
    else:
        last_day = first_day.replace(month=first_day.month + 1)
    lookup_kwargs = {'%s__range' % date_field: (first_day, last_day)}

    # Only bother to check current date if the month isn't in the past and future objects are requested.
    if last_day >= now.date() and not allow_future:
        lookup_kwargs['%s__lte' % date_field] = now
     
    # Only load the content if asked    
    if make_object_list:    
        object_list = queryset.filter(**lookup_kwargs)
        if not object_list and not allow_empty:
            raise Http404
    else:
        object_list = []
        
    # don't let the days go by
    lookup_kwargs = {'%s__month' % date_field: month}
    days = queryset.filter(**lookup_kwargs).dates(date_field, 'day')
    
    # Calculate the next month, if applicable.
    if allow_future:
        next_month = last_day + datetime.timedelta(days=1)
    elif last_day < datetime.date.today():
        next_month = last_day + datetime.timedelta(days=1)
    else:
        next_month = None

    if not template_name:
        template_name = "%s/%s_archive_monthdays.html" % (model._meta.app_label, model._meta.object_name.lower())
    t = template_loader.get_template(template_name)
    c = RequestContext(request, {
        '%s_list' % template_object_name: object_list,
        'month': date,
        'year': year,
        'next_month': next_month,
        'previous_month': first_day - datetime.timedelta(days=1),
        'days':days,    
        }, context_processors)
    for key, value in extra_context.items():
        if callable(value):
            c[key] = value()
        else:
            c[key] = value
    return HttpResponse(t.render(c), mimetype=mimetype)
