"""
     python/ui/mg_ex_utility.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC

     This library is free software: you can redistribute it and/or
     modify it under the terms of the GNU Lesser General Public License
     version 3, modified in accordance with the provisions of the 
     license to address the requirements of UK law.
 
     You should have received a copy of the modified GNU Lesser General 
     Public License along with this library.  If not, copies may be 
     downloaded from http://www.ccp4.ac.uk/ccp4license.php
 
     This program is distributed in the hope that it will be useful,
     but WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     GNU Lesser General Public License for more details.
"""


import utils
import version

class mg_ex_utility:
  '''
  Support for external python scripts - mainly to create 
  the log file to report back to ccp4mg
  '''
  
  def __init__(self,task=''):
    import time
    import os
    import string
    import sys
    # Read command line args
    self.job_id = ''
    self.task = ''
    i=1
    while i < len(sys.argv):
      if string.count(sys.argv[i],'-job_id'):
        i = i+1
        self.job_id = sys.argv[i]
      elif string.count(sys.argv[i],'-task'):
        i = i+1
        self.task = sys.argv[i]
      i = i + 1
    self.start_time = int(time.time())
    self.pid = os.getpid()

  def AppendToLog(self):
    pass

  
  def WriteLog(self,status=''):
    import os
    import time
    import string

    #Beware running from command line not CCP4mg
    if not self.job_id or not self.task: return
    
    #print "WriteLog status",status
    if self.job_id:
      path = os.path.join(utils.get_CCP4MG(),'logs',self.task+'_'+str(self.job_id)+'.log')
    else:
      path = os.path.join(utils.get_CCP4MG(),'logs',self.task+'_'+str(self.pid)+'.log')
    f = utils.openFile(path,'w',overwrite='Overwrite')
    if not f: return
    t = string.split(time.ctime(time.time()))
    date = t[2]+' '+t[1]+' '+t[4]+' '+t[3]

    stat = string.split(status)[0]
    f.write(
'#CCP4MG VERSION '+str(version.ccp4mg_version)+'\n'+
'#SCRIPT LOG '+self.task+'\n' +
'#DATE '+date+'\n'+
'#JOB_ID '+str(self.job_id)+'\n'+
'#TERMINATION STATUS '+str(stat)+'\n' +
'#REPORT '+str(status)+'\n' )
    f.close()
