#!/usr/bin/env python
import types
from os.path import join
from inspect import getsource, getmembers, isclass, isfunction, ismethod, ismodule
from importlib import import_module

root="./build/api"

# autopath

from os.path import dirname, abspath, join, normpath
import sys

HERE = dirname(abspath(__file__))
PATH = normpath(join(HERE, '..', '..'))
if PATH not in sys.path:
    sys.path.insert(1, PATH)

htmltmpl = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>{title}</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8">
<meta http-equiv="content-style-type" content="text/css">
<meta http-equiv="expires" content="0">
</head>
<body>
<pre>
{content}
</pre>
</body>
</html>
"""

def write_source(name, content):
    fh = file(join(root, name)+'.html', 'w')
    fh.write(format_html(name, content))
    fh.close()

def format_html(title, content):
    return htmltmpl.format(title=title, content=content)

def parse_module(module):
    module = import_module(module)
    write_source(module.__name__, getsource(module))
#    classes = [(cls, value) for cls, value in getattr(module, '__dict__').items() if value == types.ClassType]
    classes = getmembers(module, isclass)
    for name, obj in classes:
        write_source(module.__name__ + '.' + name, getsource(obj))
#        methods = [(meth, value) for meth, value in getattr(obj, '__dict__').items() if type(value) == types.MethodType]
        methods = getmembers(obj, ismethod)
        for meth, value in methods:
            write_source(module.__name__ + '.' + name + '.' + meth, getsource(value))

    #functions = [(func, value) for func, value in getattr(module, '__dict__').items() if type(value) == types.FunctionType]
    functions =  getmembers(module, isfunction)
    for name, obj in functions:
        write_source(module.__name__ + '.' + name, getsource(obj))

def process_modules():
    from glob import glob
    from os.path import abspath, dirname, normpath, splitext, basename
    here = abspath(__file__)
    directory = dirname(here)
    pyfiles = glob(normpath(join(directory, '..', 'tiramisu', '*.py')))
    for pyf in pyfiles:
        pyf = splitext(basename(pyf))[0]
        modname = 'tiramisu.' + pyf
        if not '__init__' in modname:
            parse_module(modname)        

    pyfiles = glob(normpath(join(directory, '..', 'tiramisu', 'test', '*.py')))
    for pyf in pyfiles:
        pyf = splitext(basename(pyf))[0]
        modname = 'tiramisu.test.' + pyf
        if not '__init__' in modname:
            parse_module(modname)        

process_modules()

