import sys
import django.forms as forms
from django.db import connection
from django.http import HttpResponse
from hgbook.comments.models import Comment, Element
from django.shortcuts import get_object_or_404, render_to_response
from django.template import Context ,RequestContext
from django.template.loader import get_template
from django.utils.simplejson import dumps 
from p_list import *
from BeautifulSoup import BeautifulSoup
import glob
import os
home_dir=os.getenv("HOME")
if home_dir=='/home/amit':    
    html_folder='/home/amit/SEES-hacks/SEESenv/web/html/'
else:
    html_folder='/home/hg/repos/SEES-hacks/SEESenv/web/html/'

def dump_queries():
    # requires settings.DEBUG to be set to True in order to work
    if len(connection.queries) == 1:
        print connection.queries
    else:
        qs = {}
        for q in connection.queries:
            qs[q['sql']] = qs.setdefault(q['sql'], 0) + 1
        for q in sorted(qs.items(), key=lambda x: x[1], reverse=True):
            print q
        print len(connection.queries)

class CommentForm(forms.Form):
    id = forms.CharField(widget=forms.HiddenInput)
    name = forms.CharField(max_length=64)
    url = forms.URLField(max_length=128, required=False)
    comment = forms.CharField(widget=forms.Textarea(attrs={
        'rows': 8, 'cols': 60
        }))
    remember = forms.BooleanField(initial=True, required=False)

def search(request):
	print request


def index(request):
	html_files = glob.glob(html_folder+'ch*.html')
#	print >> sys.stderr ,html_files	
#	print >> sys.stderr ,"just checking whether i got here"	
#	print >> sys.stderr , html_files	
	html_files.sort()
	link_list=['/review/html/'+a.split('/')[-1] for a in html_files]
#	print >> sys.stderr , html_files        
	title_list=[]
	for html_file in html_files:
		file_str=open(html_file,'r').read()			
		soup_obj=BeautifulSoup(''.join(file_str))
		title_str=soup_obj.html.head.title.string		
		title_str=unicode(title_str)		
		title_str.encode('ascii','ignore')              
		title_list.append(title_str)
	
	resp_dict=zip(link_list,title_list)
	print >>sys.stderr ,resp_dict
	return render_to_response('index.html', {'resp_dict': resp_dict })







def comments_by_chapter(id):
    objs = {}
    for c in Comment.objects.filter(element=id, hidden=False).order_by('date'):
        objs.setdefault(c.element_id, []).append(c)
    return objs

def chapter(request, id):
    template = get_template('comment.html')
    resp = {}
    for elt, comments in comments_by_chapter(id).iteritems():
            
        form = CommentForm(initial={
            'id': elt,
            'name': request.session.get('name', ''),
            })
            


    resp[elt] = template.render(RequestContext({
            'id': elt,
            'form': form,
            'length': len(comments),
            'query': comments,
            }))
    return HttpResponse(dumps(resp), mimetype='application/json')

#    queryset = Comment.objects.filter(element=id, hidden=False).order_by('date')
#    if form is None:
#        form = CommentForm(initial={
#            'id': id,
#            'name': request.session.get('name', ''),
#            })
#    try:
#        error = form.errors[0]
#    except:
#        error = ''
#    return render_to_response('comment.html', {
#        'id': id,
#        'form': form,
#        'length': len(queryset),
#        'query': queryset,
#        'newid': newid or True,
#        'error': error,
#        })





def single_com(request,id):
     
#    template = get_template('comment.html')
    resp = {}
    print >> sys.stderr ,id   
    for i in p_list[id]:	
#        form=None
        queryset = Comment.objects.filter(element=i, hidden=False).order_by('date')
                
#        if form is None:
#		form = CommentForm(initial={
#		    'id': id,
#		    'name': request.session.get('name', ''),
#        })
        if len(queryset)==0:
            resp[i] = "No"
        elif len(queryset)==1:
            resp[i]="One"
        else:
            resp[i] = len(queryset)
#            'id': i,
#           'form': form,
#            'length': len(queryset),
#            'query': queryset,
            
    return HttpResponse(dumps(resp), mimetype='application/json')
#    template = get_template('comment.html')    
#    for i in p_list[id]:	
#        form=None
#        queryset = Comment.objects.filter(element=i, hidden=False).order_by('date')
#        print queryset        
#        if form is None:
#		form = CommentForm(initial={
#		    'id': id,
#		    'name': request.session.get('name', ''),
#		    })
#       try:
#		    error = form.errors[0]
#        except:
#            error = ''
	    
#    return HttpResponse(response_list)






def chapter_count(request, id):
      
    resp = comments_by_chapter(id)
    
    for elt, comments in resp.iteritems():
              
        resp[elt] = len(comments)
     
    return HttpResponse(dumps(resp), mimetype='application/json')
    
def single(request, id, form=None, newid=None ):
    queryset = Comment.objects.filter(element=id, hidden=False).order_by('date')
    if form is None:
        form = CommentForm(initial={
            'id': id,
            'name': request.session.get('name', ''),
            })
    try:
        error = form.errors[0]
    except:
        error = ''
    return render_to_response('comment.html', {
        'id': id,
        'form': form,
        'length': len(queryset),
        'query': queryset,
        'newid': newid or True,
        'error': error,
        })

def submit(request, id):
#    print request
#    print id    
    try :    
        element=Element.objects.get(id=id,chapter='chap_intro')
    except Element.DoesNotExist:
        element=Element(id=id)    
	element.save()    
    
   
    if request.method == 'POST':
       
	form = CommentForm(request.POST)
	   
	if form.is_valid():
            data = form.cleaned_data
            
	    if data.get('remember'):
		               
		request.session['name'] = data['name']
                request.session['url'] = data['url']
            else:
                request.session.pop('name', None)
                request.session.pop('url', None)
            c = Comment(element=element,
                        comment=data['comment'],
                        submitter_name=data['name'],
                        submitter_url=data['url'],
                        ip=request.META.get('REMOTE_ADDR'))
          
			
	c.save()
        newid=c.id        
        form = None
    return single(request, id, form, newid)

