# -*- coding: utf-8 -*-

# Copyright (c) 2003 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Package implementing the scripting interface.
"""

import os
import sys

from KdeQt import KQMessageBox

from ScriptManager import *
import Preferences
import Utilities

from eric3config import getConfig

scriptManager = None
initialized = 0

def init(ui):
    """
    Module function to initialize the scripting engine.
    
    @param ui reference to the UserInterface object
    @return reference to the script manager object (ScriptManager)
    """
    global initialized, scriptManager
    
    g = globals()
    g["Eric"] = ui
    g["ViewManager"] = ui.viewmanager
    g["Project"] = ui.project
    g["DebugServer"] = ui.dbg.dbs
    g["Wizards"] = ui.wizards
    g["ConfigDir"] = Utilities.getConfigDir()
    g["InstallDir"] = getConfig('ericDir')
    g["ScriptsMenu"] = ui.scriptsMenu
    g["ScriptsToolbar"] = ui.scriptsToolBar
    g["installScript"] = installScript
    g["removeScript"] = removeScript
    g["createScript"] = createScript
    g["createDocument"] = ui.viewmanager.newEditor
    if not initialized:
        scriptManager = ScriptManager(ui, g)
        initialized = 1
        return scriptManager

def runStartupScripts(ui):
    """
    Public module function to run the startup scripts.
    
    The startup script looked for have to be named "startup.py".
    The global startup script is searched for in the eric3 installation directory.
    The user startup script is searched for in the users config directory
    (on Win32 it is _eric3, everywhere else it is .eric3) in the users home
    directory. The startup scripts found are executed in the order global startup
    the local startup. This gives the user the capability to overwrite global
    startup actions.
    
    @param ui reference to the UserInterface object
    """
    global scriptManager
    
    import Preferences
    
    globalStartup = ("global startup",
        os.path.join(getConfig('ericDir'), 
        "Scripting", "startup.py"))
    localStartup = ("local startup",
        os.path.join(Utilities.getConfigDir(),
        "startup.py"))
        
    for scriptName, script in [globalStartup, localStartup]:
        oldpwd = os.getcwd()
        try:
            f = open(script)
            startup = f.read()
            f.close()
            createScript(scriptName, startup)
            os.chdir(os.path.dirname(script))
            scriptManager.executeScript(scriptName)
            scriptManager.deleteScript(scriptName)
        except ScriptError, e:
            KQMessageBox.critical(ui,
                qApp.translate('Scripting', 'Error executing startup script'),
                qApp.translate('Scripting', 
                    '<p>The startup script <b>%1</b> could not be executed.<br>'
                    'Problem: %2</p>')
                    .arg(scriptName).arg(unicode(e)))
        except IOError:
            pass
        os.chdir(oldpwd)
    
def installScript(action, menubar = None, toolbar = None):
    """
    Module function to install a script.
    
    @param action the script action to be installed (ScriptAction)
    @param menubar the menubar this script is to be added to (QMenuBar)
    @param toolbar the toolbar this script is to be added to (QToolBar)
    """
    if menubar is not None:
        action.addTo(menubar)
        
    if toolbar is not None:
        action.addTo(toolbar)
    
def removeScript(action):
    """
    Module function to remove a script.
    
    @param action script action to be removed (ScriptAction)
    """
    action.remove()
    
def createScript(name, code):
    """
    Module function to create a new script.
    
    @param name name for the script (string or QString)
    @param code the script code (string or QString)
    @return a reference to the newly created script (ScriptAction)
    """
    global scriptManager
    return scriptManager.addScript(name, code)
