from plugin.PluginRegistry import PluginRegistry
from main import CONTROLPATHS

import os


#
# Factory for plugins. We don't look up plugins by their implementation but
# by their interface. Several plugins providing the same interface may
# co-exist.
#
class _ControlFactory:

    def __init__(self):

        self.__after_rebuilding = False

        self.__registry = PluginRegistry(*CONTROLPATHS)
        


    #
    # Returns a control providing the given interfaces.
    #
    def get_control(self, *interfaces):

        query = ""
        if (len(interfaces) == 1):
            query += "(MATCH '%s' '%s')" % (PluginRegistry.INTERFACE,
                                              interfaces[0])

        else:
            for iface in interfaces:
                query += "(AND (MATCH '%s' '%s')" \
                         % (PluginRegistry.INTERFACE, iface)
            query += ")" * len(interfaces)

        result = self.__registry.get_plugins(query)

        if (result):
            return result[0]()

        elif (not self.__after_rebuilding):
            # if we did not find the control, maybe we should rebuild the
            # controls registry and search again (once!)
            self.__registry = PluginRegistry(*CONTROLPATHS)
            self.__after_rebuilding = True
            try:
                ret = self.get_control(*interfaces)
            finally:
                self.__after_rebuilding = False

            return ret

        else:
            return


_singleton = _ControlFactory()
def ControlFactory(): return _singleton
