import importlib
import inspect
import pkgutil

from malwareconfig.common import Decoder, PreProcessor
from malwareconfig import decoders
from malwareconfig import preprocessors

def load_decoders():

    dec_modules = dict()

    # Walk recursively through all modules and packages.
    for loader, module_name, ispkg in pkgutil.walk_packages(decoders.__path__, decoders.__name__ + '.'):
        # If current item is a package, skip.
        if ispkg:
            continue
        # Try to import the module, otherwise skip.
        try:
            module = importlib.import_module(module_name)
        except ImportError as e:
            print("Unable to import Module {0}: {1}".format(module_name, e))
            continue

        for mod_name, mod_object in inspect.getmembers(module):
            if inspect.isclass(mod_object):
                if issubclass(mod_object, Decoder) and mod_object is not Decoder:
                    dec_modules[mod_object.decoder_name] = dict(obj=mod_object,
                                                                decoder_name=mod_object.decoder_name,
                                                                decoder_description=mod_object.decoder_description,
                                                                decoder_version=mod_object.decoder_version,
                                                                decoder_author=mod_object.decoder_author
                                                                )
    return dec_modules


def load_preprocessors():

    pre_modules = dict()

    # Walk recursively through all modules and packages.
    for loader, module_name, ispkg in pkgutil.walk_packages(preprocessors.__path__, preprocessors.__name__ + '.'):
        # If current item is a package, skip.
        if ispkg:
            continue
        # Try to import the module, otherwise skip.
        try:
            module = importlib.import_module(module_name)
        except ImportError as e:
            print("Unable to import Module")
            continue

        for mod_name, mod_object in inspect.getmembers(module):
            if inspect.isclass(mod_object):
                if issubclass(mod_object, PreProcessor) and mod_object is not PreProcessor:
                    pre_modules[mod_object.preprocessor_name] = dict(obj=mod_object,
                                                                     preprocessor_name=mod_object.preprocessor_name,
                                                                     preprocessor_description=mod_object.preprocessor_description,
                                                                     preprocessor_version=mod_object.preprocessor_version,
                                                                     preprocessor_author=mod_object.preprocessor_author
                                                                     )
    return pre_modules


__decoders__ = load_decoders()
__preprocessors__ = load_preprocessors()
