"""
     privateer.py: CCP4 GUI Project
     Copyright (C) 2014 University of York

     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.
"""

from CCP4PluginScript import CPluginScript
from CCP4Modules import PROCESSMANAGER
import CCP4ErrorHandling


class privateer(CPluginScript):

    TASKMODULE          = 'validation'          # Where this plugin will appear on the gui  
    TASKTITLE           = 'Validation of carbohydrate structures'  # A short title for gui menu
    TASKNAME            = 'privateer'  # Task name - should be same as class name
    TASKCOMMAND         = 'privateer'           # The command to execute, should be reachable
    DESCRIPTION='Checks stereochemistry, conformation and fit to density. Describes glycans (Privateer)'
    TASKVERSION         = 0.1                   # Version of this plugin
    WHATNEXT = ['coot_rebuild']
    MAINTAINER = 'jon.agirre@york.ac.uk'

    def processInputFiles(self):
      import CCP4XtalData
      #print 'taskMakeHklin F_SIGF',self.container.inputData.F_SIGF,type(self.container.inputData.F_SIGF),self.container.inputData.F_SIGF.contentFlag
      self.hklin,error = self.makeHklin ( [ ['F_SIGF',CCP4XtalData.CObsDataFile.CONTENT_FLAG_FMEAN ] ] )
      if error.maxSeverity()>CCP4ErrorHandling.SEVERITY_WARNING: return CPluginScript.FAILED
      
      return CPluginScript.SUCCEEDED

    def processOutputFiles(self):
        
        import os
        out = self.container.outputData
        self.path_wrk = str( self.getWorkDirectory() )

        fileName = os.path.join ( self.path_wrk, 'FPHIOUT.mtz' )
        library  = os.path.join ( self.path_wrk, 'privateer-lib.cif' )
        
        if os.path.isfile ( fileName ) :
            out.FPHIOUT.set ( fileName )
            out.FPHIOUT.annotation.set ( '2mFo-DFc map coefficients' )
            out.FPHIOUT.subType = 1

        fileName2 = os.path.join ( self.path_wrk, 'OMITFPHIOUT.mtz' )

        if os.path.isfile ( fileName2 ) :
            out.DIFFPHIOUT.set ( fileName2 )
            out.DIFFPHIOUT.annotation.set ( 'omit mFo-DFc map coefficients' )
            out.DIFFPHIOUT.subType = 2

        fileName3 = os.path.join ( self.path_wrk, 'privateer-results.py' )

        if os.path.isfile ( fileName3 ) :
            out.COOTSCRIPTOUT.set ( fileName3 )
            out.COOTSCRIPTOUT.annotation.set ( 'guided tour on the reported issues' )
        
        if os.path.isfile (library) :
            out.LIBOUT.set ( library )
            out.LIBOUT.annotation.set ( 'Dictionary containing monoperiodic torsions for fixing up distorted sugars' )
        
        return CPluginScript.SUCCEEDED

    def makeCommandAndScript(self):
      import os
      import CCP4XtalData
   
      self.appendCommandLine(['-stdin'])

      self.appendCommandScript( "pdbin %s"%(str(self.container.inputData.XYZIN)))

      # INPUT DATA
      self.appendCommandScript( "mtzin "+self.hklin )
      self.appendCommandScript( "mode ccp4i2" )
      self.appendCommandScript( "colin-fo F,SIGF")
      
      # CONTROL PARAMETERS

      if self.container.controlParameters.SHOWGEOM:
        self.appendCommandScript("showgeom")
      
      if self.container.controlParameters.RADIUSIN.isSet():
        self.appendCommandScript("radiusin %s"%(str(self.container.controlParameters.RADIUSIN))) 
      
      if self.container.controlParameters.NEW_SUGAR :
        self.appendCommandScript("valstring %s,%s/%s/%s/%s/%s/%s,%s,%s,%s"%(self.container.controlParameters.CODEIN,self.container.controlParameters.RING_OXYGEN,self.container.controlParameters.RING_C1,self.container.controlParameters.RING_C2,self.container.controlParameters.RING_C3,self.container.controlParameters.RING_C4,self.container.controlParameters.RING_C5,self.container.controlParameters.ANOMER,self.container.controlParameters.HAND,self.container.controlParameters.CONFORMATION_PYRANOSE ))
        self.appendCommandScript("codein %s"%(self.container.controlParameters.CODEIN))
        
      if self.container.controlParameters.VERTICAL == "vertical" :
        self.appendCommandScript("vertical")
      
      if self.container.controlParameters.ESSENTIALS == "essentials" :
        self.appendCommandScript("essentials")
      
      if self.container.controlParameters.INVERT == "white" :
        self.appendCommandScript("invert")
        
      if self.container.controlParameters.EXPRESSION != "undefined" :
        self.appendCommandScript("expression %s" % (self.container.controlParameters.EXPRESSION) )
      
      
#      OUTPUT DATA
#      if self.container.outputData.XYZOUT.isSet():
#          self.appendCommandScript("pdbout %s"%(str(self.container.outputData.XYZOUT.fullPath)))
#      self.appendCommandScript("xmlout %s"%(self.makeFileName('PROGRAMXML')))

      return CPluginScript.SUCCEEDED


#=============================================================================================
import unittest
class testPrivateer(unittest.TestCase):
  
  def test1(self):
    # Test creation of log file using ../test_data/test1.params.xml input
    from CCP4Utils import getCCP4I2Dir
    import CCP4Utils, os
    workDirectory = CCP4Utils.getTestTmpDir()
    logFile = os.path.join(workDirectory,'privateer_test1.log')
    # Delete any existing log file
    if os.path.exists(logFile): os.remove(logFile)
    self.wrapper = privateer(name='privateer_test1',workDirectory=workDirectory)
    self.wrapper.container.loadDataFromXml(os.path.join(getCCP4I2Dir(),'wrappers','privateer','test_data','test1.params.xml'))
    self.wrapper.setWaitForFinished(1000000)
    pid = self.wrapper.process()
    self.wrapper.setWaitForFinished(-1)
    if len(self.wrapper.errorReport)>0: print self.wrapper.errorReport.report()
    #self.assertTrue(os.path.exists(logFile),'No log file found')


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

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