"""
     freerflag.py: CCP4 GUI Project
     Copyright (C) 2011 STFC
"""

from CCP4PluginScript import CPluginScript
import CCP4ErrorHandling

class freerflag(CPluginScript):

    TASKMODULE = 'test'      # Where this plugin will appear on the gui
    TASKTITLE = 'Add a freeR flag' # A short title for gui menu
    TASKNAME = 'freerflag'   # Task name - should be same as class name
    TASKVERSION= 0.0               # Version of this plugin
    MAINTAINER = 'liz.potterton@york.ac.uk'

    # used by the base class startProcess()
    TASKCOMMAND = 'freerflag'   # The command to run the executable
    # used by the base class makeCommandAndScript()
    COMLINETEMPLATE = None 
    COMTEMPLATE = None  

    def processInputFiles(self):
      if self.container.controlParameters.GEN_MODE == 'COMPLETE':
        # ignoreErrorCodes to say makeHklin can ignore cmtzjoin gices exitCode 101 for incomplete freerflag
        self.hklin,error = self.makeHklin(['F_SIGF','FREERFLAG'],ignoreErrorCodes=[36])
        print 'freerflag.processInputFiles',self.hklin,error
        if error.maxSeverity()>CCP4ErrorHandling.SEVERITY_WARNING:
          return CPluginScript.FAILED
        else:
          return CPluginScript.SUCCEEDED
      else:
        self.hklin = self.container.inputData.F_SIGF.__str__()
        return CPluginScript.SUCCEEDED

    def processOutputFiles(self):

      from lxml import etree

      with open ( self.makeFileName('PROGRAMXML'),'w' ) as xmlFile:
         xmlRoot = etree.Element('freerflag')
         xmlString = etree.tostring ( xmlRoot, pretty_print=True )
         xmlFile.write(xmlString)

      if self.container.controlParameters.GEN_MODE == 'COMPLETE':
         self.container.outputData.FREEROUT.annotation = 'Extended set of freeR flags'
      else:
         self.container.outputData.FREEROUT.annotation = 'New set of freeR flags'

      if self.container.controlParameters.GEN_MODE == 'COMPLETE':
          error = self.splitHklout(['FREEROUT'],['FREER'])
      else:          
          error = self.splitHklout(['FREEROUT'],['FreeR_flag'])

      if error.maxSeverity()>CCP4ErrorHandling.SEVERITY_WARNING:
        return CPluginScript.FAILED
      else:
        return CPluginScript.SUCCEEDED

    def makeCommandAndScript(self):
      import os
      self.hklout = os.path.join(self.workDirectory,"hklout.mtz")

      self.appendCommandLine(['HKLIN', self.hklin])
      self.appendCommandLine(['HKLOUT', self.hklout])

      print "FRAC isSet", self.container.controlParameters.FRAC.isSet()

      if self.container.controlParameters.GEN_MODE == 'COMPLETE':
          if self.container.inputData.FREERFLAG.isSet():
            self.appendCommandScript("COMPLETE FREE=FREER")
          else:
            self.appendErrorReport(101)
            
      # FREERFLAG keyword only applies if not completing existing freeR set
      elif self.container.controlParameters.FRAC.isSet():
          self.appendCommandScript("FREERFRAC %s"%(str(self.container.controlParameters.FRAC)))

      if self.container.controlParameters.UNIQUEIFY:
          self.appendCommandScript("UNIQUE")
          if self.container.controlParameters.RESMAX:
              self.appendCommandScript("RESOL %s"%(str(self.container.controlParameters.RESMAX)))

      self.appendCommandScript('END')

      return 0

#======================================================
# PLUGIN TESTS
# See Python documentation on unittest module

import unittest

class testfreerflag(unittest.TestCase):

   def setUp(self):
    import CCP4Modules
    self.app = CCP4Modules.QTAPPLICATION()
    # make all background jobs wait for completion
    # this is essential for unittest to work
    CCP4Modules.PROCESSMANAGER().setWaitForFinished(10000)

   def tearDown(self):
    import CCP4Modules
    CCP4Modules.PROCESSMANAGER().setWaitForFinished(-1)

   def test_1(self):
     import CCP4Modules, CCP4Utils, os

     workDirectory = CCP4Utils.getTestTmpDir()
     # this needs to agree with name attribute below
     logFile = os.path.join(workDirectory,'test1_freerflag.log')
     # Delete any existing log file
     if os.path.exists(logFile): os.remove(logFile)

     self.wrapper = freerflag(parent=CCP4Modules.QTAPPLICATION(),name='test1',workDirectory=workDirectory)
     self.wrapper.container.loadDataFromXml(os.path.join(CCP4Utils.getCCP4I2Dir(),'wrappers','freerflag','test_data','test1.data.xml'))

     self.wrapper.setWaitForFinished(1000000)
     pid = self.wrapper.process()
     self.wrapper.setWaitForFinished(-1)
     if len(self.wrapper.errorReport)>0: print self.wrapper.errorReport.report()

   def test_2(self):
     import CCP4Modules, CCP4Utils, os

     workDirectory = CCP4Utils.getTestTmpDir()
     # this needs to agree with name attribute below
     logFile = os.path.join(workDirectory,'test2_freerflag.log')
     # Delete any existing log file
     if os.path.exists(logFile): os.remove(logFile)

     self.wrapper = freerflag(parent=CCP4Modules.QTAPPLICATION(),name='test2',workDirectory=workDirectory)
     self.wrapper.container.loadDataFromXml(os.path.join(CCP4Utils.getCCP4I2Dir(),'wrappers','freerflag','test_data','test2.data.xml'))

     self.wrapper.setWaitForFinished(1000000)
     pid = self.wrapper.process()
     self.wrapper.setWaitForFinished(-1)
     if len(self.wrapper.errorReport)>0: print self.wrapper.errorReport.report()

def TESTSUITE():
  suite = unittest.TestLoader().loadTestsFromTestCase(testfreerflag)
  return suite

def testModule():
  suite = TESTSUITE()
  unittest.TextTestRunner(verbosity=2).run(suite)
