"""This server implementation encodes the CAPTCHA ID poorly."""

import web
from Captcha.Visual import Text, Backgrounds, Distortions, ImageCaptcha
from Captcha import Words

urls = ('/', 'index', '/(.*).jpg', 'image')

ids = []

class WeakCaptcha(ImageCaptcha):
    def __init__(self, word):
        self.word = word
        ImageCaptcha.__init__(self)
    
    def getLayers(self):
        self.addSolution(self.word)
        return [    Backgrounds.CroppedImage(), 
                    Text.TextLayer(self.solutions[0]), 
                    Distortions.SineWarp()  ]


class index:
    def GET(self):
        id = Words.defaultWordList.pick().encode('rot13')
        ids.append(id)
        print """<html><body>
<p><img src="%s.jpg"/></p>
<p><form action="/" method="post">
    Enter the word shown:
    <input type="hidden" name="id" value="%s" />
    <input type="text" name="word" />
</form></p>
</body></html>
""" % (id, id)
    
    def POST(self):
        i = web.input('id', 'word')
        if (i.id in ids) and (i.id.decode('rot13') == i.word):
            print "Passed"
            ids.remove(i.id)
        else:
            print "Fail!"

class image:
    def GET(self, id):
        print WeakCaptcha(id.decode('rot13')).render().tostring('jpeg', 'RGB')

if __name__ == '__main__': web.run(urls, globals(), web.reloader)