from django.template import RequestContext
from django.conf import settings
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from ox.django.shortcuts import json_response, render_to_json_response, get_object_or_404_json

#from api.views import html_snapshot
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse

'''
def index(request):
    context = RequestContext(request, {'settings':settings})
    if request.GET.get('_escaped_fragment_', None):
        return html_snapshot(request)
    return render_to_response('index.html', context)
'''

def autocomplete(request, ctype_id):
    q = request.GET.get('q', '')
    if q == '':
        q = 'a'
    page = int(request.GET.get('page', '1'))
    page_limit = int(request.GET.get('page_limit', '10'))
    ctype = get_object_or_404_json(ContentType, pk=ctype_id)
    model_class = ctype.model_class()
    #model_class = ContentType.objects.get_for_id(ctype_id)
    qset = model_class.get_qset()
    all_results = model_class.fts(qset, q)
    paginator = Paginator(all_results, page_limit)
    results = paginator.page(page)
    items = [obj.autocomplete_dict() for obj in results.object_list]
    ret = {
        'items': items,
        'has_next': results.has_next()
    }
    return render_to_json_response(ret)


def popup_form(request, ctype_id):
    ctype = get_object_or_404(ContentType, pk=ctype_id)
    model_class = ctype.model_class()
    form_class = model_class.get_popup_form()
    if request.POST:
        form = form_class(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False, request=request)
            if instance.__dict__.has_key('added_by_id'):
                instance.added_by = request.user
            instance.save()
            text = instance.get_title()
            return HttpResponse("<script>opener.dismissAddAnotherPopup(window, '%s', '%s')</script>" % (instance.id, text,))
    else:
        form = form_class()
    context = RequestContext(request, {
        'form': form
    })
    return render_to_response("test/popup.html", context)


def site_json(request):
  data = {
    'site': {
      'name': 'India Theatre Forum.'
    }
  }
  return render_to_json_response(data)

