# Create your views here.

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from django.http import HttpResponseRedirect

from django_demo.comments.models import Post, User, Captcha

def index(request):

	htmlString = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\
	<html>\
	<head>\
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8">\
	<meta name="viewport" content="width=device-width, user-scalable=no"/>\
	<title>Django Comment Test Page</title>\
	</head>\
	<body>\
	This is a demo bulletin board I wrote using Django and the Python language. <br/>\
	It is running on my Apache/2.2.15 (Unix) PHP/5.3.2 mod_wsgi/3.2 Python/2.6.5 server.<br/> Post a comment...\
	<form name="test" action="/django_demo/recvcom/" method="post">\
	'
	
	cap = Captcha()
	cap.addSession(request)
	htmlString += cap.question
	
	htmlString += '\
	<input style="width:30px;" name="captchaInput" id="captchaInput" value="">\
	<!--<label>Name:</label><input name="user_name" class="textbox">!-->\
	<div style="margin-top:12px;"></div>\
	<textarea name="content"></textarea>\
	<input onclick="vCap(this)" type="button" value="Post">\
	<script language="javascript">\
	function vCap(buttonObj)\
	{\
		var capInput = document.getElementById("captchaInput");\
		if(capInput.value != '+`cap.answer`+')\
		{\
			alert("Answer captcha math problem before posting");\
		}\
		else\
		{\
			buttonObj.form.submit();\
		}\
	}\
	</script>\
	</form>'
	
	queryResult = Post.objects.order_by('-created')

	for p in queryResult:
		
		u = User.objects.get(id=p.user_id)
		htmlString += '<div class="comment_container" style="margin-top:12px;">'
		htmlString += '<span style="color:blue;">Posted by '+ u.ip_address + ' @ ' + p.created.strftime("%Y-%m-%d %H:%M:%S") + "</span>"
		htmlString += '<br/>'
		htmlString += '<div class="comment" style="border:1px dashed black;">'
		htmlString += p.content
		htmlString += '</div></div>'
		
	htmlString += '\
	</body>\
	</html>'

	
	return HttpResponse(htmlString)

@csrf_exempt
def recvcom(request):
	u = User(name="anonymous", ip_address=request.META['REMOTE_ADDR'] )
	u.save()
	
	if User.objects.filter(ip_address=request.META['REMOTE_ADDR']).count() > 10:
		return HttpResponse('lo siento no mas')
		
	
	import datetime
	p = Post(content=request.POST['content'], user_id=u.id, created=datetime.datetime.now())
	if request.POST['captchaInput'] == "":
		return HttpResponse("answer the captcha before posting")
	
	if `request.session['captchaAnswer']` != request.POST['captchaInput']:
		return HttpResponse("invalid captcha answer")
		#return HttpResponse("postinput=" + request.POST['captchaInput'] + "capAnswer=" + `request.session['captchaAnswer']`)
		
	p.save()	
		
	return HttpResponseRedirect("/django_demo/comments")