""" module loader. """

import logging
import importlib
import inspect
import obj
import os
import pkgutil
import time
import types

table = {}

class Loader(obj.Object):

    def cached(self, name):
        global table
        if name not in table:
            table[name] = self.direct(name) 
        return table[name]

    def direct(self, name, package=None):
        logging.debug("load %s" % name)
        try:
            p, m = name.split(" .", 1) 
            return importlib.import_module(m, p)
        except ValueError:
            return importlib.import_module(name)

    def init(self, m):
        func = getattr(m, "init", None)
        if func:
            return obj.launch(func)

    def load_mod(self, name, mod=None):
        mod = mod or self.cached(name)
        for key, func, modname in self.scan_commands(mod):
            obj.names[key] = modname
        return mod

    def register(self, cmd, handler):
        handlers[cmd] = handler

    def scan_commands(self, mod):
        for key in dir(mod):
            if key.startswith("_"):
                continue
            o = getattr(mod, key, None)
            if o and isinstance(o, types.FunctionType):
                if "event" in o.__code__.co_varnames:
                    yield (key, o, mod.__name__)
            elif o and isinstance(o, obj.Object):
                t = obj.get_type(o)
                if t not in obj.types:
                    obj.types.append(t)
                cls = t.split(".")[-1]
                if cls not in obj.classes:
                    obj.classes[cls.lower()] = t

    def unload(self, modname):
        global handlers, table
        if modname in table:
            mod = table[modname]
        for key, func, name in self.scan(mod):
            if name == modname:
                try:
                    del handlers[key]
                    del names[key]
                except KeyError:
                    pass

