import sys
import traceback


def load_plugin(module_name, *args):
    """
    This function creates an instance of a class that's inside a module
    with the same name.

    Example :
    >>> spider = factory( 'w3af.plugins.crawl.google_spider' )
    >>> spider.get_name()
    'google_spider'

    :param module_name: Which plugin do you need?
    :return: An instance.
    """
    try:
        __import__(module_name)
    except ImportError, ie:
        msg = 'There was an error while importing %s: "%s".'
        raise Exception(msg % (module_name, ie))
    except Exception, e:
        msg = 'There was an error while importing %s: "%s".'
        raise Exception(msg % (module_name, e))
    else:

        class_name = module_name.split('.')[-1]

        try:
            module_inst = sys.modules[module_name]
            a_class = getattr(module_inst, class_name)
        except Exception, e:
            msg = 'The requested plugin ("%s") doesn\'t have a correct' \
                  ' format: "%s".'
            raise Exception(msg % (module_name, e))

        try:
            inst = a_class(*args)
        except Exception, e:
            msg = 'Failed to get an instance of "%s". Original exception:'\
                  ' "%s". Traceback for this error: %s'
            msg = msg % (class_name, e, traceback.format_exc())
            raise Exception(msg)

        for required_method in ('get_host', 'get_port', 'use_ssl',
                                'get_request_str'):
            if not getattr(inst, required_method):
                msg = 'The plugin needs to implement "%s"' % required_method
                raise Exception(msg)

        return inst
