from datetime import datetime

from django.conf import settings
from django.template.context import RequestContext
from django.views.generic import list_detail
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

DEFAULT_TEMPLATE = 'visitors/sections/default.html'
from visitors.models import *
from darkroom.models import Webcam

def index(request):
    edition=VisitorsEdition.objects.latest()
    cams=Webcam.objects.all()
    return render_to_response('visitors/index.html', locals(),
                              context_instance=RequestContext(request))

def section_index(request):
    sections = Section.objects.filter(published=True, featured=True,
            pub_date__lte=datetime.now,
            featured_on__lte=datetime.now,
            featured_until__gte=datetime.now)
    return render_to_response('visitors/section_index.html', locals(),
                              context_instance=RequestContext(request))

def section_detail(request, slug):
    section=get_object_or_404(Section, slug=slug)
    if section.template_name:
        t = loader.select_template((section.template_name, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)
    
    c = RequestContext(request, {
        'section': section,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, Section, section.id)
    return response

def attraction_index(request):
    attractions=Attraction.objects.filter(published=True,
            pub_date__lte=datetime.now())
    categories=Category.objects.all()
    return render_to_response('visitors/attraction_index.html', locals(),
                              context_instance=RequestContext(request))

def category_detail(request, slug):
    category=get_object_or_404(Category, slug=slug)
    attractions=Attraction.objects.filter(categories=category)
    return render_to_response('visitors/category_index.html', locals(),
                              context_instance=RequestContext(request))


def attraction_detail(request, category_slug, slug):
    category=get_object_or_404(Category, slug=category_slug)
    attraction=get_object_or_404(Attraction, slug=slug)

    if attraction.point:
	latitude=attraction.point.lat_lon.split(",")[0]
	longitude=attraction.point.lat_lon.split(",")[1]
        
    gmaps_api_key=settings.GOOGLE_API_KEY
    return render_to_response('visitors/attraction_detail.html', locals(),
                              context_instance=RequestContext(request))

def visitors_edition_detail(request, slug):
    edition = get_object_or_404(VisitorEdition, slug=slug)
    return render_to_response('visitors/visitor_edition_detail.html', locals(),
                              context_instance=RequestContext(request))
