#!/usr/bin/env python
# coding=utf-8
 
__author__ = 'Paul Morel', 'Brian McFadden', 'Adams Tower'
__copyright__ = '© Copyright 2012 Tartan Solutions, Inc.'
__credits__ = ('Paul Morel', 'Michael Rea', 'Dan Hummon',
                       'Brian McFadden', 'Adams Tower')
__license__ = 'MIT'
__maintainer__ = 'Adams Tower <adams.tower@tartansolutions.com>'
__version__ = version = __VERSION__ = VERSION = '0.1'
__status__ = 'Alpha'
 
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from plaidcloud.container import Container
import cgi
 
 
class HelloHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        if ctype == 'multipart/form-data':
            postvars = cgi.parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers.getheader('content-length'))
            postvars = cgi.parse_qs(self.rfile.read(length),
                                    keep_blank_values=1)
        elif ctype == 'application/json':
            length = int(self.headers.getheader('content-length'))
            postvars = cgi.parse_qs(self.rfile.read(length),
                                    keep_blank_values=1)
        else:
            postvars = {}
        handle = postvars['handle'][0]
        container = Container()
        container.parseHandle(handle)
        self.process(container)
        self.wfile.write(container.get_response())
 
    def process(self, data):
        print 'request received'
        #print data.template
        data.info("Hello, Client!")
 
 
def run_server():
    try:
        server = HTTPServer(('', 8000), HelloHandler)
        print 'server started'
        server.serve_forever()
    except KeyboardInterrupt:
        print 'server shutting down...'
        server.socket.close()
 
 
if __name__ == '__main__':
    run_server()