# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA

import sys

def is_importable(modulename,name):
    """ Check whether a certain module is available.
    """
    try:
        __import__(modulename, globals(), {}, [name])
        return 1
    except ImportError:
        raise
        return 0

def get_modules(file,subdir=None):
    import os, re
    dir = os.path.dirname(file)
    if subdir:
        dir = os.path.join(dir,subdir)
    regex = re.compile(r"^([^_].*)\.py$")
    dirlist = []
    if os.path.exists(dir):
        dirlist = os.listdir(dir)
    files = filter(None, map(regex.match, dirlist))
    modules = map(lambda x: x.group(1), files)
    modules.sort()
    return modules


def import_name(modulename, name):
    """ Import name dynamically from module

    Used to do dynamic import of modules and names that you know their
    names only in runtime.

    Any error raised here must be handled by the caller.

    @param modulename: full qualified mudule name, e.g. x.y.z
    @param name: name to import from modulename
    @rtype: any object
    @return: name from module
    """
    module = __import__(modulename, globals(), {}, [name])
    return getattr(module, name)


