import os
try:
    from django import newforms as forms
except ImportError:
    from django import forms
from django.conf import settings
from reportlab.pdfbase.pdfutils import _fusc
from rlextra.graphics.captcha import getCaptcha

def _captchaFusc(t,d=0):
    f = _fusc('delugujoqehocexihesekumiweto',7)
    if not d:
        c = ''.join(['%2.2x' %  x for x in map(ord,f.encrypt(t))])
        n = len(c)>>1
        return c[n:]+c[:n]
    else:
        n = len(t)>>1
        c = t[n:]+t[:n]
        n <<= 1
        c = ''.join([chr(eval('0x'+c[i:i+2])) for i in xrange(0,n,2)])
        return f.decrypt(c)

class CaptchaForm(forms.Form):
    verification_code = forms.CharField(max_length=5, required=True, widget=forms.TextInput(attrs={'style': 'width: 100%;'})) #where you enter the text

    def __init__(self, *args, **kwargs):
        super(CaptchaForm, self).__init__(*args, **kwargs)
        t = None
        for arg in args:
            if 't' in arg:
                t = arg['t']
                break
        if not t:
            t, captcha = getCaptcha(fontSize=16)
            t = _captchaFusc(t)
            captchaFile =  'captcha_%s.gif' % t
            file(os.path.join(settings.OUTDIR, captchaFile), 'wb').write(captcha)
        captchaFile =  'captcha_%s.gif' % t
        self.fields['t'] = forms.CharField(widget=forms.HiddenInput(attrs={'value': t})) #has obfuscated captcha text
        self.imageLabel = '<img src="%s/%s" alt="captcha" border="1"/>' % (settings.OUTDIR_HTTP, captchaFile)
        self.fields['verification_code'].label = self.imageLabel

    def clean(self):
        super(CaptchaForm, self).clean()
        if 't' in self.data and 'verification_code' in self.data:
            if _captchaFusc(self.data['t'], d=1) != self.data['verification_code']:
                raise forms.ValidationError('Your verification code was wrong, please try again.')

    def as_table(self):
        "Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
        s = '<tr><th style="vertical:align: middle;">' + self.imageLabel + '</th><td style="vertical:align: middle;">%(errors)s%(field)s%(help_text)s</td></tr>'
        return self._html_output(s, u'<tr><td colspan="2">%s</td></tr>', '</td></tr>', u'<br />%s', False)

    def as_ul(self):
        "Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
        s = '<li>%(errors)s' + self.imageLabel + ' %(field)s%(help_text)s</li>'
        return self._html_output(s, u'<li>%s</li>', '</li>', u' %s', False)

    def as_p(self):
        "Returns this form rendered as HTML <p>s."
        s = '<p> ' + self.imageLabel + '&nbsp;%(field)s%(help_text)s</p>'
        return self._html_output(s, u'%s', '</p>', u' %s', True)
