# This file is part of the Coral project.
# Please read the copyright notice in the LICENSE file.

from coral.core.transform.pipeScript import *
from coral import kernel

def spyrun(script,namespace=None,exceptHook=None,strict=0):
    if namespace is None:
        namespace={}

    toExecute=pipeParse(script+"\n",0)
   
    #if Project.theProject:
    #    namespace["model"]=Project.theProject.getRoot()
    #else:

    namespace["model"]=None

    if not namespace.has_key("sys"):
        namespace["sys"]=sys

    namespace["__builtins__"]=__builtins__

    #if Project.theProject.getRoot():
    #    defaultCode="from "+Project.theProject.getRoot().getMetamodel().__name__+" import *\n"
    #else:

    defaultCode=""
            
    #defaultCode=defaultCode+"from smw.command import *\n"+"from smw.transform import pipeScript\n"

    code=compile(defaultCode,'<CoralShell>','exec')
    exec(code,namespace)

    ok=1
    isExpression=1
    try:
        code=compile(toExecute,'<CoralShell>','eval')
    except:
        isExpression=0
        if exceptHook:
            try:
                code=compile(toExecute,'<Coralhell>','exec')
            except:
                exceptHook()
        else:
            code=compile(toExecute,'<CoralShell>','exec')

    result=None

    if code:
        kernel.getTransactionManager().beginModifyCmd(strict)
        try:
            if exceptHook:
                try:
                    result=eval(code,namespace)
                except:
                    ok=0                
                    exceptHook()
            else:
                result=eval(code,namespace)
              
        finally:
            kernel.getTransactionManager().endModifyCmd()

        #if kernel.getTransactionManager().canUndo() and not ok:
        #    print("*** Previous changes in the model are reverted due to this error. ***\n")
        #    kernel.getTransactionManager().undo()
                
    return (result,not ok)       

def main(args):
    r = PipeScriptRunner(args).doit()
    
if __name__ == '__main__':
    import sys
    main(sys.argv[1:])

