import tornado.web
import tornado.ioloop
from emotionnaise_modules import face, misc

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('<html><body><form action="/" method="POST" enctype="multipart/form-data">'
                   '<input type="file" name="image" accept="image/*">'
                   '<input type="submit">'
                   '</form></body></html>')

    def post(self):
        data = self.request.files['image'][0]['body']
        image = misc.image_from_buffer(data)

        faces = face.find_faces(image)
        if len(faces) == 0:
            self.write('<html><body>No faces found</body></html>')
            return

        f = face.Face(image, faces[0])
        b64 = misc.image_to_base64(f.get_marked_image())
        
        res = '<html><body><div>{json}</div><img src="data:image/png;base64,{base64}"></body></html>'.format(json=f.to_JSON(), base64=b64)
        self.write(res)


class JSONHandler(tornado.web.RequestHandler):
    def post(self):
        data = self.request.files['image'][0]['body']
        image = misc.image_from_buffer(data)

        faces = face.find_faces(image)
        if len(faces) == 0:
            self.write({})
        else:
            f = face.Face(image, faces[0])

            self.write(f.to_dict())


application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/json", JSONHandler),
])

if __name__ == '__main__':
    application.listen(8080)
    tornado.ioloop.IOLoop.current().start()
