from random import randrange,randint
from Captcha.Visual.Tests import PseudoGimpy
import sys, datetime
from cursesite.utils.template import render_template
from django.core.validators import ValidationError
from django.conf import settings
from django.views.decorators.cache import cache_control

CAPTCHA_TIMEOUT = 360 # 360 minutes -- 6 hours

@cache_control(no_cache=True)
def show_captcha(request):
	from django.http import HttpResponse
	response = HttpResponse()
	response['Content-type'] = "image/png"
	g = PseudoGimpy()
	i = g.render()
 	i.save(response, "png")
 	safe_solutions = [hash(s) for s in g.solutions]
	response.set_cookie('captcha', safe_solutions, max_age=None, expires=None, 
		domain=settings.SESSION_COOKIE_DOMAIN)
	return response

class CaptchaMiddleware:
	def __init__(self):
		self.captcha_check = False
		
	def checkCaptcha(self, data):
		if not self.captcha_solutions:
			raise ValidationError, "Cookies required to register"
	
		if str(hash(data)) not in self.captcha_solutions:
			raise ValidationError, "Text incorrect"
			
	def process_request(self, request):
		if (request.user.is_authenticated() and (request.user.mobile_verified or request.user.is_staff)) or not settings.ENABLE_CAPTCHA:
			return
		if request.POST and ('_ish' not in request.COOKIES or datetime.datetime.fromtimestamp(float(request.COOKIES.get('_ish', 0))) < datetime.datetime.now()-datetime.timedelta(minutes=CAPTCHA_TIMEOUT)):
			error = None
			self.captcha_solutions = request.COOKIES.get('captcha', None)
			if 'captcha' in request.POST:
				try:
					self.checkCaptcha(request.POST.get('captcha'))
				except ValidationError, msg:
					print msg
					error = msg
				else:
					self.captcha_check = True
					return
			ec = {
				'error': error,
				'random_num': randint(1, sys.maxint),
				'url': request.path,
				'post_data': request.POST,
			}
			return render_template(request, 'captcha.html', ec)

	def process_response(self, request, response):
		from time import time
		if self.captcha_check:
			response.set_cookie('_ish', int(time()), max_age=None,
			expires=datetime.datetime.now()+datetime.timedelta(hours=CAPTCHA_TIMEOUT), 
			domain=settings.SESSION_COOKIE_DOMAIN)
		return response