from django import forms
from django.forms import Widget
from django.forms.util import ValidationError

# http://pypi.python.org/pypi/recaptcha-client, tested with 1.0.2
from recaptcha.client import captcha

class RecaptchaWidget(Widget):
    def __init__(self, pubkey, **kwargs):
        Widget.__init__(self, **kwargs)
        self.public_key = pubkey
    
    def value_from_datadict(self, data, files, name):
        return (data.get('recaptcha_challenge_field'), data.get('recaptcha_response_field')) 

    def render(self, name, value, attrs=None):
        return captcha.displayhtml(self.public_key)

class RecaptchaField(forms.Field):
    def __init__(self, public_key, private_key, ip_addr, **kwargs):
        self.widget = RecaptchaWidget(public_key)
        self.ip_addr = ip_addr
        self.private_key = private_key
        forms.Field.__init__(self, **kwargs)
    
    def clean (self, value):
        ret = captcha.submit(value[0], value[1], self.private_key, self.ip_addr)
        if ret.is_valid:
            return "success"
        else:
            raise ValidationError("Recaptcha Failed")
    
