from main import HOME, SENSORPATHS
from config.ConfigManager import ConfigManager
from utils import dialog

import os, sys

if "." not in sys.path: sys.path.append(".")
if HOME not in sys.path: sys.path.append(HOME)


#
# Factory class for dynamically loaded Sensors.
#
class _SensorFactory:

    def __init__(self):

        # a set to remember the modules loaded so far
        self.__modules = {}

        # get instance of the configuration manager
        self.__config = ConfigManager()



    #
    # Creates and returns a Sensor of the given type or None if the Sensor
    # could not be created.
    #
    def create_sensor(self, name, args):

        # find and import the sensor
        oldcwd = os.getcwd()
        sensor = None
        module = None

        try:

            for p in SENSORPATHS:

                try:
                    os.chdir(p)
                except OSError:
                    continue

                # reload old modules to force using the latest version; this
                # means we can edit modules while running gDesklets
                # TODO: clean up
                        
                try:
                    sensordir = os.path.abspath(name)
                    if (not os.path.exists(sensordir)): continue
                    
                    if name in self.__modules:
                        module, path = self.__modules[name]
                        reload(module)
                    else:
                        if (name in sys.modules): del sys.modules[name]
                        module = __import__(name)
                        path = sensordir

                    break

                except ImportError, e:
                    import traceback; traceback.print_exc()
                    print e
                    continue

                except Exception, e:
                    dialog.warning(
                        _("Error in sensor '%(name)s'") % vars(),
                        _("An error occured while loading a sensor. "
                          "This most likely means that your system does not "
                          "fulfill all its requirements."))
                    # a stack trace could be useful for debugging sensors
                    import traceback; traceback.print_exc()
                    print e
            #end for

            if (module):
                self.__modules[name] = (module, path)
                # initalize the sensor

                try:
                    os.chdir(path)
                    sensor = module.new_sensor(args)
                except:
                    dialog.warning(_("Error in sensor %(name)s") % vars(),
                                   _("An error occured while running a sensor."))
                    # a stack trace could be useful for debugging sensors
                    import traceback; traceback.print_exc()

            else:
                print "Could not load sensor %(name)s" % vars()
                dialog.warning(
                    _("Could not find sensor '%(name)s'") % vars(),
                    _("A sensor could not be found. This usually means that "
                      "it has not been installed."), show_traceback = True)


            return sensor

        finally:
            os.chdir(oldcwd)


_singleton = _SensorFactory()
def SensorFactory(): return _singleton
