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 = "marketplace/guide/default.html"
from marketplace.models import *


def index(request):
    categories = Category.objects.all()
    features = Business.objects.filter(status=3)[:3]
    guides = Guide.objects.filter(published=True, pub_date__lte=datetime.now)
    return render_to_response(
        "marketplace/index.html", locals(), context_instance=RequestContext(request)
    )


def category_index(request, slug):
    category = get_object_or_404(Category, slug=slug)
    subcategories = Subcategory.objects.filter(category=category)
    businesses = Business.objects.filter(categories=category)
    return render_to_response(
        "marketplace/category_index.html",
        locals(),
        context_instance=RequestContext(request),
    )


def subcategory_index(request, category_slug, slug):
    category = get_object_or_404(Category, slug=category_slug)
    subcategory = get_object_or_404(Subcategory, slug=slug)
    businesses = Business.objects.filter(subcategories=subcategory)
    return render_to_response(
        "marketplace/subcategory_index.html",
        locals(),
        context_instance=RequestContext(request),
    )


def business_detail(request, slug):
    business = get_object_or_404(Business, slug=slug)
    if business.hours_set.all():
        hours = business.hours_set.all()

    if business.dininghours_set.all():
        dining_hours = business.dininghours_set.all()

    if business.menu_set:
        menus = business.menu_set.all()

    if business.point:
        latitude = business.point.lat_lon.split(",")[0]
        longitude = business.point.lat_lon.split(",")[1]

    gmaps_api_key = settings.GOOGLE_API_KEY
    return render_to_response(
        "marketplace/business_detail.html",
        locals(),
        context_instance=RequestContext(request),
    )


def guide_index(request):
    guides = Guide.objects.filter(
        published=True, featured=True, pub_date__lte=datetime.now
    )
    return render_to_response(
        "marketplace/guide_index.html",
        locals(),
        context_instance=RequestContext(request),
    )


def guide_detail(request, slug):
    guide = get_object_or_404(Guide, slug=slug)
    if guide.template_name:
        t = loader.select_template((guide.template_name, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)

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