#!/usr/bin/env python
# system
### Twisted Preamble
# This makes sure that users don't have to set up their environment
# specially in order to run these programs from bin/.
import sys, os, string
if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]
), os.pardir, os.pardir)))
sys.path.insert(0, os.curdir)
### end of preamble

import os, sys

# ***** RISE FROM YOUR GRAVE! *****
import twisted.web.microdom
sys.modules['xml'] = twisted
twisted.dom = twisted.web
sys.modules['xml.dom'] = twisted.web
twisted.web.minidom = twisted.web.microdom
sys.modules['xml.dom.minidom'] = twisted.web.microdom

#it'd be nice to get this working
def myimport(*args):
    try: 
        return im(*args)
    except:
        mod = FakeModule(args[0], 4)
        i = args[0].rfind('.')
        if i != -1:
            setattr(sys.modules[args[0][:i]], args[0][i+1:], mod)
        return mod

class FakeModule:

    def __init__(self, name, level):
        self.__level = level
        self.__name__ = name

    def __repr__(self):
        return '<Fake %s>' % self.__name__
    __str__ = __repr__

    def __nonzero__(self):
        return 1

    def __call__(self, *args, **kw):
        pass #print 'Called:', args

    def __getattr__(self, attr):
        if self.__level == 0:
            raise AttributeError
        return FakeModule(self.__name__+'.'+attr, self.__level-1)

    def __cmp__(self, other):
        if not hasattr(other, '___name__'):
            return -1
        return cmp(self.__name__, other.__name__)

def fakeOut(modname):
    modpath = modname.split('.')
    prevmod = None
    for m in range(len(modpath)):
        mp = '.'.join(modpath[:m+1])
        nm = FakeModule(mp, 4)
        if prevmod:
            setattr(prevmod, modpath[m], nm)
        sys.modules[mp] = nm
        prevmod = nm
        print mp

if not os.environ.get("DISPLAY"):
    fakeOut("gnome.ui")
    fakeOut("pygtk")
    fakeOut("gtk")
    fakeOut("wxPython.wx")

# initial twisted
from twisted.python import reflect
from twisted.internet import reactor
# epydoc
from epydoc.cli import cli
from epydoc.html import HTMLFormatter

def _uid_to_uri(self, uid):
    if uid.is_module() or uid.is_class():
        return uid.name() + '.html'

    parent = uid.parent()
    if parent is None:
        return uid.name() + '.html'

    return parent.name() + '.html#' + uid.shortname()
HTMLFormatter._uid_to_uri = _uid_to_uri

modnames = []
def addMod(arg, path, files):
    for fn in files:
        file = os.path.join(path, fn).replace('/__init__', '')
        if file[-3:] == '.py' and not file.count('/test/'):
            modName = file[2:-3].replace('/','.')
            try:
                #print 'pre-loading', modName
                reflect.namedModule(modName)
            except ImportError:
                print 'import error:', modName
            except:
                print 'other error:', modName
            else:
                modnames.append(modName)
osrv = sys.argv
sys.argv=["IGNORE"]
im = __import__
__builtins__.__import__ = myimport
os.path.walk('./twisted', addMod, None)
__builtins__.__import__ = im
sys.argv = osrv
sys.argv.extend(modnames)              # list of modules
cli()
print 'Done!'
