# Create your views here.
from django.shortcuts import render_to_response
from models import Issue
from settings import ERANG_SUBSCRIBE_URL
import urllib2
from django.http import HttpResponse
from django.core.mail import send_mail
from django.db.models import Q
from ox.django.shortcuts import render_to_json_response
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt

RESULTS_PER_PAGE = 6

def home(request):
  all_issues = Issue.objects.all().order_by('-date')
  if request.GET.has_key('issue_id'):
    issue_id = request.GET.get('issue_id')
  else:
#    l = 0
    issue_id = all_issues[0].id    
  current_issue = Issue.objects.get(pk=issue_id)
  other_issues = all_issues.exclude(pk=issue_id)
  hasCommented = request.GET.has_key('c')
  return render_to_response("erang/home.html", {
    'current_issue': current_issue,
    'hasCommented': hasCommented
#    'past_issues': other_issues
  }, context_instance=RequestContext(request))

def issue_list(request):
  p = RESULTS_PER_PAGE
  try:
    page_no = int(request.GET.get("page", '1'))
  except ValueError:
    page_no = 1

#  print start_no
  search_terms = request.GET.get("search", "")
#  print search_terms
  if search_terms != '':
    qset = search(search_terms)
  else:
    qset = Issue.objects.all()

  qset = qset.order_by('-date')
  paginator = Paginator(qset, p)
  
  try:
    results = paginator.page(page_no)
  except (EmptyPage, InvalidPage):
    results = paginator.page(paginator.num_pages)

  issues = []
  for r in results.object_list:
    d = r.get_dict()
    issues.append(d)

  return render_to_json_response({
    'hasPrev': results.has_previous(),
    'hasNext': results.has_next(),
    'issues': issues,
    'page_no': page_no,
    'search_terms': search_terms
  })
     

@csrf_exempt
def subscribe(request):
  email = request.POST.get("email")
  url = ERANG_SUBSCRIBE_URL + email
  re = urllib2.urlopen(url).read()
  return HttpResponse(re)
  
def search(terms):
#  terms = request.GET['search']
  words = terms.split(" ")
  qset = Issue.objects.all()
  issues = []
  for w in words:
    qset = qset.filter(Q(title__icontains=w) | Q(summary__icontains=w))
  return qset

  '''
  for issue in qset:
    d = issue.get_dict()
    issues.append(d)
  return issues  
  '''

'''
def postfeedback(request):
  p = request.POST
  issue = p.get("issue")
  name = p.get("name")
  email = p.get("email")
  comment = p.get("comment")
  txt = """
    Feedback on Issue: %s
    
    Name: %s
    Email: %s
    Feedback %s
  """ % (issue, name, email, comment,)
  send_mail("eRang Feedback", txt, "do-not-reply@theatreforum.in", ['sanjaybhangar@gmail.com', 'erang@theatreforum.in'])
  return HttpResponse("1")   
'''
