
from CCP4PluginScript import CPluginScript

class csymmatch(CPluginScript):

    TASKTITLE='Csymmatch - move model to a reference by using symmetry'
    TASKNAME = 'csymmatch'
    TASKMODULE = 'molecular_replacement'
    TASKCOMMAND = 'csymmatch'
    TASKVERSION = 0.0
    ASYNCHRONOUS = False
    MAINTAINER = 'liz.potterton@york.ac.uk'

    def makeCommandAndScript(self):

      inp = self.container.inputData
      par = self.container.controlParameters
      out = self.container.outputData

      import CCP4Utils
      import os

      self.appendCommandLine( [ '-pdbin' , inp.XYZIN_QUERY.fullPath.__str__() ] )
      self.appendCommandLine( [ '-pdbin-ref' ,  inp.XYZIN_TARGET.fullPath.__str__()  ] )
      if par.ORIGIN_HAND.isSet():
        if par.ORIGIN_HAND:
          self.appendCommandLine( [ '-origin-hand'] )
      if par.CONNECTIVITY_RADIUS.isSet():
        self.appendCommandLine( [ '-connectivity-radius',str(par.CONNECTIVITY_RADIUS)] )
      self.appendCommandLine( [ '-pdbout' , out.XYZOUT.fullPath.__str__() ] )

    def processOutputFiles(self):
        logName = self.makeFileName('LOG')
        
        from lxml import etree
        xmlRoot = etree.Element('Csymmatch')
        segmentNode = None
        with open (logName,'r') as logFile:
            lines = logFile.readlines()
            for line in lines:
                if line.strip().startswith('Change of hand'):
                    handNode = etree.SubElement(xmlRoot,'ChangeOfHand')
                    handNode.text = line.strip().split(':')[1]
                elif line.strip().startswith('Change of origin'):
                    originNode = etree.SubElement(xmlRoot,'ChangeOfOrigin')
                    originNode.text = line.strip().split(':')[1]
                elif line.strip().startswith('Chain'):
                    segmentNode = etree.SubElement(xmlRoot,'Segment')
                    rangeNode = etree.SubElement(segmentNode,'Range')
                    rangeNode.text = line.strip().split('will')[0]
                elif line.strip().startswith('Symmetry operator'):
                    if segmentNode is not None:
                        operatorNode = etree.SubElement(segmentNode,'Operator')
                        operatorNode.text = line.strip().split(':')[1]
                elif line.strip().startswith('Lattice shift'):
                    if segmentNode is not None:
                        shiftNode = etree.SubElement(segmentNode,'Shift')
                        shiftNode.text = line.strip().split(':')[1]
                elif line.strip().startswith('with normalised score'):
                    if segmentNode is not None:
                        scoreNode = etree.SubElement(segmentNode,'Score')
                        scoreNode.text = line.strip().split(':')[1]
    
        with open(self.makeFileName('PROGRAMXML'),'w') as xmlFile:
            xmlString = etree.tostring(xmlRoot, pretty_print=True)
            xmlFile.write(xmlString)


        return CPluginScript.SUCCEEDED
#---------------------------------------------
import unittest

class testcsymmatch( 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 test1( self ) :

      import CCP4Modules, CCP4Utils, os

      workDirectory = CCP4Utils.getTestTmpDir()
      xmlInput = os.path.join( CCP4Utils.getCCP4I2Dir(), 'wrappers', 'csymmatch', 'test_data', 'test1'+'.params.xml' )
      self.wrapper = csymmatch(parent=CCP4Modules.QTAPPLICATION(), name='csymmatch_test1',workDirectory=workDirectory)
      self.wrapper.container.loadDataFromXml( xmlInput )

      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( testcsymmatch )
   return suite

def testModule() :

   suite = TESTSUITE()
   unittest.TextTestRunner( verbosity=2 ).run( suite )

