#!/usr/bin/python
# Copyright (C) 2009 Christoph Egger
# 
#   This software is provided 'as-is', without any express or implied
#   warranty.  In no event will the authors be held liable for any damages
#   arising from the use of this software.
# 
#   Permission is granted to anyone to use this software for any purpose,
#   including commercial applications, and to alter it and redistribute it
#   freely, subject to the following restrictions:
# 
#   1. The origin of this software must not be misrepresented; you must not
#      claim that you wrote the original software. If you use this software
#      in a product, an acknowledgment in the product documentation would be
#      appreciated but is not required.
#   2. Altered source versions must be plainly marked as such, and must not be
#      misrepresented as being the original software.
#   3. This notice may not be removed or altered from any source distribution.

import os.path
import markdown

basepath='__FILL_IN__'

templatename = '%s/template' % basepath

datadir = '%s/data' % basepath

template = file(templatename, 'r').read().decode('utf-8')

def checkdir(dirname, base):
	import os
	
	content = [i for i in os.listdir(dirname) if i not in ['.hg', 'chatprotokolle', 'komponenten', 'tex'] ]
	
	posdelta = dirname.replace('%s/data/' % basepath, '')[1:]
	
	posdelta = '%s/' % posdelta if len(posdelta) > 0 else posdelta
	
	dirs = [i for i in content if os.path.isdir('%s/%s' % (dirname, i))]
	mdns = [i for i in content if os.path.isfile('%s/%s' % (dirname, i)) and os.path.splitext(i)[1] == '.mdn']
	
	return '<ul>%s%s</ul>' % ( '\n'.join([ '<li class="mdnfile"><a href="%s">%s</a></li>' % 
                                               ('%s/%s%s' % (base, posdelta, os.path.splitext(i)[0]),
                                                os.path.splitext(i)[0]) for i in mdns ]),
                                   '\n'.join([ '<li class="directory"><a href="%s">%s</a>\n%s</li>' % 
                                               ('%s/%s/%s' % (base, posdelta, i), i, checkdir('%s/%s' % (dirname, i), base)) for i in dirs ])) 

def render_mdn(what):
    data = file(what, 'r').read().decode('utf-8')
    return template % markdown.markdown(data)

def mdnserver(environment, start_response):
    start_response('200 OK', [('Content-Type', 'application/xhtml+xml')])

    what = '%s/%s.mdn' % (datadir, environment.get('PATH_INFO', ''))

    if os.path.isfile(what):
        return [ render_mdn(what).encode('utf-8') ]

    dirlisting = template % checkdir(what[:-4],environment.get('SCRIPT_NAME', ''))
    return [  dirlisting.encode('utf-8') ]

application = mdnserver

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    httpd = make_server('', 8000, mdnserver)
    httpd.serve_forever()

