#!/usr/bin/env /usr/bin/ecell3-python

import sys
import string
import getopt
import os

import ecell.emc
import ecell.GtkSessionMonitor
import gtk
import gobject

#FIXME: commandline processing needed

def usage():
    aProgramName = os.path.basename( sys.argv[0] )
    print '''
%s -- invoke ecell3 python intract mode or run ess file

Usage:

       %s [-f] [-f emlfile]          : Load eml file 
				       and invoke ecell3 intract mode
       %s [essfile] [-e essfile]     : Run ess file
       %s                            : Invoke ecell3 intract mode
       %s [-h]                       : Print this message
       
Options:

       -e or --exec=[.ess file]           :  load script (.ess) file
       -f or --file=[.eml file]           :  load model (.eml) file
       
       Do not use -e and -f at same time.
       
       -DNAME=VALUE                       :  Set session parameter
       --parameters="[python dictionary]" :  Set session parameters
        
       eaxmple: 

       ecell3-session -DNAME1=VALUE1 -DNAME2=VALUE2
       ecell3-session --parameters="{NAME1:VALUE1,NAME2:VALUE2}"

       Do not use space in Variable.

       -h or --help              :  Print this message.

Configurations:

       If the environment variable ECELL3_DM_PATH is set to a colon (:) 
       separated directory path, it loads dynamic modules from there.
       
       example: 
        
       ECELL3_DM_PATH=/home/user/dm:/home/user/dm_other ecell3-session

'''% ( aProgramName, aProgramName, aProgramName, aProgramName, aProgramName )

def startInteract( aTupple ):
	aSession = aTupple[0]
	aParameters = aTupple[1]
        aSession.interact( aParameters )

def loadScript( aTupple ):
	aSession = aTupple[0]
	aParameters = aTupple[1]
	anEssFile = aTupple[2]
        aSession.loadScript( anEssFile, aParameters )

def main():

    # -------------------------------------
    # initialize file names
    # -------------------------------------
    anEmlFile = None
    anEssFile = None
    anEmlFlag = 0

    aParameters = {}

    # -------------------------------------
    # when ecell3-session [ essfile ] check file exist
    # and set anESSfile 
    # -------------------------------------

    if len( sys.argv ) == 2:	
        if not (sys.argv[1])[0] == "-":
            if not os.path.isfile( sys.argv[1] ):
                print "File Name Error: "+ sys.argv[1] + " is not Exist."
                
            anEssFile = sys.argv[1]

    # -------------------------------------
    # gets options
    # -------------------------------------
    try:
        opts , args = getopt.getopt( sys.argv[1:] , 'he:f:D:',
                                     ["parameters=","help", "exec=", "file="])
    except:
        usage()
        sys.exit(1)
        
    # -------------------------------------
    # checks argument
    # -------------------------------------
    for anOption, anArg in opts:

        # prints help message
        if anOption in ( "-h", '--help' ):
            usage()
            sys.exit(0)
            
        # executes script file (.ess)
        if anOption in ( "-e", '--exec'):
            if not anArg:
                print "Warning: not specify ess file"
                usage()
		sys.exit(0)
	    anEssFile = anArg
            
        # load model file (.eml)
        if anOption in ( "-f", '--file' ):
            if not anArg:
                print "Warning: not specify eml file"
                usage()
		sys.exit(0)
            anEmlFile = anArg            

	# set session parameters            
        if anOption == "-D":
            aSplitArgList = string.split(anArg,'=')

            if not aSplitArgList[1]:
                aSplitArgList[1] = 1
            
            try:
                anEvaluatedString = eval(aSplitArgList[1])
                aParameters[aSplitArgList[0]] = anEvaluatedString
            except:
                aParameters[aSplitArgList[0]] = aSplitArgList[1]

	# set session parameters            
        if anOption == "--parameters":
            try:
                anEvaluatedArg = eval(anArg)

            except:
                import traceback 
                aErrorMessageList = traceback.format_exception(sys.exc_type,sys.exc_value,sys.exc_traceback)
                for aLine in aErrorMessageList: 
                    print aLine 
                print 'Error : %s is not evaluate.' %anArg
                print '%s is not python dictionary and do not use space in variable.' %anArg
                sys.exit(0)

            # check anEvaluatedArg type
            if not type(anEvaluatedArg) == dict:
                print 'Error : %s is not python dictionary.' %aParameters
                sys.exit(0)

            # add parameters to aParameters 
            for aKeyString in anEvaluatedArg.keys():
                aParameters[aKeyString] = anEvaluatedArg[aKeyString]
                
            
    aSimulator = ecell.emc.Simulator()
    aSession = ecell.GtkSessionMonitor.GtkSessionMonitor( aSimulator )

    if anEmlFile:
        aSession.loadModel(anEmlFile)

    if anEssFile:

	gobject.timeout_add( 1, loadScript, [aSession, aParameters, anEssFile] )

    else:
	gobject.timeout_add( 1, startInteract, [aSession, aParameters] )
    aSession.GUI_interact()

         
if __name__ == '__main__':
	main()
