#!/usr/bin/env python
import os, sys
sys.path.append(".")

sys.path.append("./FeatureServer")


from FeatureServer.Server import wsgiApp, wsgiHandler, cfgfiles, theServer, Server

def list_dists():
    dist_list = os.listdir("dists")
    dist_html = map(lambda x: "<li><a href='/dists/%s'>%s</a></li>" % (x,x), dist_list)
    html = "<html><head><title>Software Distributions</title></head><body><ul>%s</ul></body></html>" % "\n".join(dist_html)
    return html 

def myapp (environ, start_response):
    mimetypes = { 'gz':'application/x-tar', 
                  'zip':'application/zip', 
                  'png': 'image/png', 
                  'jpeg':'image/jpeg', 
                  'js':'application/x-javascript',
                  'css':'text/css',
                  'swf':'application/x-shockwave-flash'}
    global theServer
    cfgs    = cfgfiles
    if not theServer:
        theServer = Server.load('conf/featureserver.cfg')
    path = environ['PATH_INFO']
    parts = path.split("/")
    if parts[-1] == "" and path != "/": 
        path += "index.html"
        parts[-1] = "index.html" 
    mime = "text/html"
    
    splits = parts[-1].split(".")
    mime = mimetypes.get(splits[-1], "text/html")
    
    if path == "/":
        start_response("200 OK", [('Content-Type',mime)])
        return [str(open("./docs/index.html").read())]    
    elif path == "/docs/fs.html":
        try:
            os.stat("docs/tiles")
            start_response("200 OK", [('Content-Type',mime)])
            return [str(open("./docs/fs.html").read())]    
        except OSError, E:
            start_response("200 OK", [('Content-Type',mime)])
            return [str(open("./docs/fs-wms.html").read())]    
            
    if "/docs" == path[0:5]:
        start_response("200 OK", [('Content-Type',mime)])
        return [str(open(".%s" % path, "rb").read())]   
    
    if "/dists" == path[0:6]:
        if len(parts) > 2:
            start_response("200 OK", [('Content-Type',mime)])
            return [str(open(".%s" % path, "rb").read())]
        else:
            start_response("200 OK", [('Content-Type',"text/html")])
            return [str(list_dists())]   
        
    return wsgiHandler(environ, start_response, theServer)

if __name__ == '__main__':
    from wsgiref import simple_server
    httpd = simple_server.WSGIServer(('',8080), simple_server.WSGIRequestHandler,)
    print "Listening on port 8080"
    print "Browse to http://localhost:8080/ to view demos."
    httpd.set_app(myapp)
    httpd.serve_forever()
