
import os,sys

def getCCP4I2Dir(up=1):
	target = os.path.join(os.path.realpath(sys.argv[0]),"..")
	abstarget = os.path.abspath(target)
        splittarget = abstarget.split()
        if splittarget.count('ccp4i2'):
          splittarget.reverse()
          up = splittarget.index('ccp4i2')
        while up>0:
          abstarget = os.path.dirname(abstarget)
          up = up -1
        return abstarget

def quitThread(thread):
  import sys
  print 'quitThread',thread; sys.stdout.flush()
  #thread.quit()
  #thread.wait()
  import CCP4Modules
  CCP4Modules.QTAPPLICATION(graphical=False).quit()
  sys.exit()

  
if __name__ == '__main__':

    import sys,os
    # Redirect stderr to stdout
    sys.stderr = sys.stdout
    print 'runTask sys.argv',sys.argv
    top_path = getCCP4I2Dir()
    execfile(os.path.join(top_path,'utils','startup.py'))
    graphical = False
    
    if graphical:
      setupPythonpath(mode='qtgui')
    else:
      setupPythonpath(mode='qtcore')
    setupPluginsPath()

    configFile = None
    dbFile = None
    dbXmlFile = None
    iarg = 2
    while iarg < len(sys.argv):
      if sys.argv[iarg] == '-dbxml':
        if iarg+1 <  len(sys.argv):
	      iarg += 1
	      dbXmlFile = sys.argv[iarg]
      elif sys.argv[iarg][0:2] == '-c':
        if iarg+1 <  len(sys.argv):
	      iarg += 1
	      configFile = sys.argv[iarg]
      elif sys.argv[iarg] == '-db':
        if iarg+1 <  len(sys.argv):
	      iarg += 1
	      dbFile = sys.argv[iarg]
      print 'runTask iarg',iarg,'dbFile',dbFile,'dbXmlFile',dbXmlFile,'configFile',configFile
      iarg += 1
    # Use the specified config file or dbFile
    import CCP4Config
    if configFile is not None:
      config = CCP4Config.CONFIG(sys.argv[2])
      print 'Running plugin using config file:',configFile
    else:
      config = loadConfig()
    config.set('graphical',graphical)
    if dbFile is not None and os.path.exists(dbFile):
      print 'Running plugin using database file:',dbFile
      config.set('dbFile',dbFile)

    # Get name of plugin and whether it is asynchronous
    async = False
    import CCP4PluginScript,CCP4File,CCP4Modules
    if os.path.splitext(sys.argv[1])[1] == '.xml':
      comFilePath = sys.argv[1]
      compressedFile = None
      try:
        xmlHeader = CCP4File.CI2XmlHeader()
        xmlHeader.loadFromXml(sys.argv[1],checkValidity=False)
        #print 'runTask pluginName',xmlHeader,xmlHeader.pluginName
        async = CCP4Modules.TASKMANAGER().getPluginScriptClass(str(xmlHeader.pluginName)).ASYNCHRONOUS
      except:
        pass
    else:
      comFilePath = None
      compressedFile = sys.argv[1]
    #if not async:
    #if compressedFile is not None or dbXmlFile is not None:
    #Running remotely - need to redirect stdout/stderr
    #startPrintHandler(app)
      
    if 0:
      print 'Run non-asynchronous task',xmlHeader.pluginName
      runPlugin = CCP4PluginScript.CRunPlugin(None,top_path,comFilePath=comFilePath,compressedFile=compressedFile,dbXmlFile=dbXmlFile)
      runPlugin.run()
      sys.exit(app.exec_())
    else:
      #print 'Run ASYNCHRONOUS task',xmlHeader.pluginName
      print 'Running QApplication to support asyncronous sub-processes'
      import CCP4RunPluginThread
      from PyQt4 import QtCore
      import functools
      app = CCP4Modules.QTAPPLICATION(graphical=graphical)
      #runPlugin = CCP4RunPluginThread.CRunPluginThread(app,top_path,sys.argv[1])
      runPlugin = CCP4PluginScript.CRunPlugin(app,top_path,comFilePath=comFilePath,compressedFile=compressedFile,dbXmlFile=dbXmlFile)
      app.connect(app,QtCore.SIGNAL('aboutToQuit()'),functools.partial(quitThread,runPlugin))
      app.connect(runPlugin,QtCore.SIGNAL('finished()'),functools.partial(quitThread,runPlugin))
      runPlugin.run()
      sys.exit(app.exec_())
