#------------------------------------------------------------------------------
# $Id$
# $URL$
# Copyright (c) 2006, Ilias Lazaridis - All Rights Reserved
#------------------------------------------------------------------------------

from trac.core import *
from trac.env import IEnvironmentSetupParticipant

import os.path
import os
       
#------------------------------------------------------------------------------

class PluginLoader(Component):
    """ (draft) Loads further plugins from the plugin/ directory
    
    the plugins don't need to have a egg-info, it will be generated from this
    component. 
    
    The plugins are loaded and enabled without manual intervention.
    
    This way it is possible to check-out and activate multiple plugins via
    svn-externals directly from svn repositories.
    
    """

    def __init__(self):
        # retrieve directory of tracx and tracx/plugins
        from tracx import __file__ as tracx_file
        tracxdir = os.path.split(os.path.dirname(tracx_file)) [0]
        self.log.debug("tracx, loading plugins form: %s", tracxdir)
       
        plugindir =  os.path.join(tracxdir, 'plugins')  
        files = os.listdir(plugindir)
        
        # create a list of subdirectories
        subdirs = []
        for file in files:
            fullname = os.path.join(plugindir,file)
            if os.path.isdir( fullname ):
                subdirs.append(fullname)
        
        # create the egg-info for each subdir
        curdir = os.getcwd()
        for dir in subdirs:
            os.chdir(dir)
            if os.path.exists( os.path.join(dir,'setup.py')):
                import sys                
                #TODO: pass argv in the global dict of the execfile function
                sys.argv = ["setup.py", "egg_info"]
                execfile( os.path.join(dir,'setup.py'))
                self.log.debug(dir)

        os.chdir(curdir)
        
        # call plugin loader      
#TODO: trac:#4317 - replace next line with below after fixing
        from tracx.modified.loader import load_components
        #trac.loader import load_components
#        
        load_components(self.env, subdirs)
        
#TODO trac:$4190 - replace dummies to force component initialization
    implements(IEnvironmentSetupParticipant)
    # IEnvironmentSetupParticipant
    def environment_created(self): pass
    def environment_needs_upgrade(self, db): return False
    def upgrade_environment(self, db): pass
#