#!/usr/bin/env python
"""

"""
import os
import sys

from os import listdir, walk
from os.path import dirname, isdir, abspath, split, join, exists


samplerpath = dirname(abspath(__file__))
packagepath, packagename = split(samplerpath)

samplerpath += os.path.sep
packagepath += os.path.sep


def namedimport(name):
    """ import a module given a dotted package name

    Taken directly from the Python library docs for __import __
    """
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod


def ispackage(path):
    return isdir(path) and exists(join(path, '__init__.py'))


def ismodule(path):
    head, tail = os.path.split(path)
    if tail in ('__init__.py', '__init__.pyc', '__init__.pyo'):
        return False
    head, tail = os.path.splitext(path)
    return tail in ('.py', ) # don't use these, which filters them out dupes ( '.pyc', '.pyo')


def listimports(top):
    top = abspath(top)
    yield top
    for path in listdir(top):
        path = join(top, path)
        if ispackage(path):
            yield path
            for subpath in listimports(path):
                yield subpath
        elif ismodule(path):
            yield path


def listmodules():
    if samplerpath not in sys.path:
        sys.path.append(samplerpath)

    dirs = [join(samplerpath, d) for d in listdir(samplerpath)]
    dirs = [d for d in dirs if exists(join(d, '__init__.py'))]

    modules = []    
    for dirname in dirs:
        dirpath = join(samplerpath, dirname)
        for path in listimports(dirpath):
            path = path.replace('.py', '')
            path = path.replace(samplerpath, '').replace(os.path.sep, '.')
            try:
                module = namedimport(path)
            except (ValueError, ImportError, ), exc:
                print 'Exception %s importing %s' % (exc, path, )
            else:
                modules.append((path, module))
    modules.sort()
    return [(path, SamplerModule(module)) for path, module in modules]


class SamplerModule(object):
    defaultIcon = 'filenew'


    def __init__(self, module):
        self.module = module


    def name(self):
        return self.module.__name__.split('.')[-1]


    def labelText(self):
        return getattr(self.module, 'labelText', self.name())


    def icon(self):
        return getattr(self.module, 'iconName', self.defaultIcon)


    def builder(self):
        for name in ('buildWidget', 'buildDialog', 'buildApp', 'MainFrame'):
            try:
                return getattr(self.module, name)
            except (AttributeError, ):
                pass
        raise AttributeError('No builder found')
