"""
     qtgui/loadPlugins.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     Copyright (C) 2009-2011 University of York

     This library is free software: you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public License
     version 3, modified in accordance with the provisions of the 
     license to address the requirements of UK law.
 
     You should have received a copy of the modified GNU Lesser General 
     Public License along with this library.  If not, copies may be 
     downloaded from http://www.ccp4.ac.uk/ccp4license.php
 
     This program 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 Lesser General Public License for more details.
"""
import sys
import os
import exceptions
import glob
import traceback
import time

loaded_funcs = []
_loaded_plugins = []

def setPluginsPath(funcName='initializePlugin'):
        pluginpaths=os.path.join(os.environ["CCP4MG"],os.path.join('qtgui','plugins'))
        plugins =  glob.glob(os.path.join(pluginpaths,'*'))
        sys.path.append(pluginpaths)
        for pluginpath in plugins:
          sys.path.append(pluginpath)

def loadPlugins(funcName='initializePlugin'):
        #import time
        #"""
        if funcName in loaded_funcs:
          return _loaded_plugins
        loaded_funcs.append(funcName)
        #"""
        if os.environ.has_key("CCP4MG_DEBUG_TIMING"):
          start = time.time()
 	loaded_plugins = []
        pluginpaths=os.path.join(os.environ["CCP4MG"],os.path.join('qtgui','plugins'))
        plugins =  glob.glob(os.path.join(pluginpaths,'*'))
        modules = []
        sys.path.insert(0,pluginpaths)
        modules.extend(glob.glob(os.path.join(pluginpaths,'*.pyo')))
        modules.extend(glob.glob(os.path.join(pluginpaths,'*.pyc')))
        modules.extend(glob.glob(os.path.join(pluginpaths,'*.py')))
        modules.extend(glob.glob(os.path.join(pluginpaths,'*.pyd')))
        modules.extend(glob.glob(os.path.join(pluginpaths,'*.so')))
        for pluginpath in plugins:
          sys.path.insert(0,pluginpath)
          modules.extend(glob.glob(os.path.join(pluginpath,'*.pyo')))
          modules.extend(glob.glob(os.path.join(pluginpath,'*.pyc')))
          modules.extend(glob.glob(os.path.join(pluginpath,'*.py')))
          modules.extend(glob.glob(os.path.join(pluginpath,'*.pyd')))
          modules.extend(glob.glob(os.path.join(pluginpath,'*.so')))
        loaded = {}
        for module in modules:
         if module.find('_Shadow.py')<0:
          modfname = os.path.basename(module)
          mod=modfname.split('.')[0]
          if not loaded.has_key(mod):
	      """
            if DEVELOPER():
              loaded_module=__import__(mod)
              if hasattr(loaded_module,funcName):
                f = getattr(loaded_module,funcName,None)
                f()
                loaded[mod] = mod
                loaded_plugins.append(loaded_module)
            else:
	      """
              if os.environ.has_key("CCP4MG_DEBUG_TIMING"):
                t1 = time.time()
              try:
                loaded_module=__import__(mod)
                if hasattr(loaded_module,funcName):
                  try:
                    f = getattr(loaded_module,funcName,None)
                    f()
                    loaded[mod] = mod
                    loaded_plugins.append(loaded_module)
                    #print dir(loaded_module)
                    #print loaded_module.__doc__
                  except:
                    print "plugin",modfname,'failed to load'
                    exc_type, exc_value,exc_tb = sys.exc_info()[:3]
                    print exc_type
                    print exc_value
                    traceback.print_tb(exc_tb)
              except:
                exc_type, exc_value = sys.exc_info()[:2]
                if str(exc_value)[:len('dynamic module does not define init function')] == 'dynamic module does not define init function':
			pass
                else:
			if exceptions.OSError == exc_type:
				pass
			elif hasattr(exceptions,"WindowsError") and exceptions.WindowsError == exc_type:
				pass
 			else:
              			print "Could not load plugin",modfname
              			print exc_type
              			print exc_value
              if os.environ.has_key("CCP4MG_DEBUG_TIMING"):
                t2 = time.time()
                print "time to load plugin",mod, funcName, t2 - t1
                        
        if os.environ.has_key("CCP4MG_DEBUG_TIMING"):
          print 'Time to load plugins (loadPlugins)',time.time()-start
        import MGApplication
        mainwin = MGApplication.GetMainWindow()
        mainwin.drawMenu("Display")
        mainwin.drawMenu("Tools")
        mainwin.drawMenu("Applications")
        _loaded_plugins.extend(loaded_plugins)
        return list(set(_loaded_plugins))
 
