"""
    ShelxCD_gui.py
    Copyright (C) 2014 Newcastle University
    Author: Martin Noble
    
    """

from PyQt4 import QtGui,QtCore

from CCP4TaskWidget import CTaskWidget

#-------------------------------------------------------------------
class ShelxCE_gui(CTaskWidget):
    #-------------------------------------------------------------------
    
    # Subclass CTaskWidget to give specific task window
    TASKMODULE = 'test'                               # Where this plugin will appear on the gui
    TASKTITLE = 'Experimental phasing from heavy atom sites with ShelxE'     # A short title for gui menu
    SHORTTASKTITLE = 'Phasing -ShelxE'     # A short title for gui menu
    DESCRIPTION = 'Phasing, density modification and autobuilding'
    TASKVERSION = 0.1
    TASKNAME = 'ShelxCE'                                  # Task name - should be same as class name
    MGDISPLAYFILES = ['XYZOUT']
    
    def __init__(self,*args,**kw):
        super(ShelxCE_gui,self).__init__(*args, **kw)
    
    def drawContents(self):
        self.openFolder(folderFunction='inputData')
        
        import CCP4Utils,CCP4Modules
        if not (hasattr(CCP4Modules.PREFERENCES(),'SHELXDIR')) and CCP4Utils.which('shelxc') is None:
            if (not CCP4Modules.PREFERENCES().SHELXDIR.exists()) and CCP4Utils.which('shelxc') is None:
              self.createLine ( [ 'warning','The Shelx programs have not been found. They are not part of CCP4 but you can get them from\nhttp://shelx.uni-ac.gwdg.de/SHELX/download.php\nIf you already have them make sure they are on the search path\nOR specify where they are in the Preferences window - under Other Software.' ])
          
        self.createLine ( [ 'label','Experiment type','stretch','tip','What sort of data are available','widget','MODE' ] )
        self.openSubFrame( frame=[True])
        self.createLine(['widget','-guiLabel','Heavy atom coordinates','HAIN'])
        self.closeSubFrame()
        self.openSubFrame( frame=True)
        
        self.createLine(['advice','Anomalous (SAD) dataset'],toggle=['MODE','open', ['SAD']])
        self.createLine(['widget','SAD'],toggle=['MODE','open', ['SAD']])

        self.openSubFrame( toggle=['MODE','open',['MAD']])
        self.createLine(['advice','High energy remote dataset'])
        self.createLine(['widget','HREM'])
        self.createLine(['advice','Low energy remote dataset'])
        self.createLine(['widget','LREM'])
        self.createLine(['advice','Inflection point dataset'])
        self.createLine(['widget','INFL'])
        self.createLine(['advice','Peak dataset'])
        self.createLine(['widget','PEAK'])
        self.closeSubFrame()

        self.createLine(['advice','Derivative dataset'],toggle=['MODE','open',['SIR']])
        self.createLine(['widget','SIR'],toggle=['MODE','open',['SIR']])

        self.createLine(['advice','Anomalous derivative dataset'], toggle=['MODE','open',['SIRAS']])
        self.createLine(['widget','SIRA'], toggle=['MODE','open',['SIRAS']])
        
        self.createLine(['advice','Native dataset'])
        self.createLine(['widget','NAT'])

        self.createLine(['advice','Radiation damaged dataset'], toggle=['MODE','open',['RIP']])
        self.createLine(['widget','RIP'], toggle=['MODE','open',['RIP']])

        self.createLine(['advice','Radiation damaged anomalous dataset'], toggle=['MODE','open',['RIPAS']])
        self.createLine(['widget','RIPA'], toggle=['MODE','open',['RIPAS']])
        self.closeSubFrame()
        
        self.ShelxCEKeywords()
    
    def ShelxCEKeywords(self):
        #From here on, GUI is autogenerated from the keywords container
        self.openSubFrame( frame=[True] )
        self.autoGenerate(container=self.container.keywords,selection={'includeParameters' : ['i','h','z','sX','aN','n','q','mN']})
        self.closeSubFrame()
    
    def isValid(self):
        inp = self.container.inputData
        requires = {
            'SAD':[inp.SAD],
            'MAD':[inp.HREM,inp.LREM,inp.INFL,inp.PEAK],
            'SIR':[inp.SIR,inp.NAT],
            'SIRAS':[inp.SIRA,inp.NAT],
            'RIP':[inp.RIP,inp.NAT],
            'RIPAS':[inp.RIPA,inp.NAT],}
        modeStr = self.container.controlParameters.MODE.__str__()

         # Need to unset the unused inputs before calling the CTaskWidget.isValid() or invalid data
        # will be flagged to user
        for fObj in [inp.SAD,inp.HREM,inp.LREM,inp.INFL,inp.PEAK,inp.SIR,inp.SIRA,inp.RIP,inp.RIPA]:
          if fObj not in requires[modeStr]: fObj.unSet()
              
        invalidElements = super(ShelxCE_gui,self).isValid()
        if modeStr == 'MAD':
            nset = len([setDataset for setDataset in requires['MAD'] if setDataset.isSet()])
            if nset < 2:
                for require in requires[modeStr]:
                    # Check whether all of the datasets required by this mode are set
                    if not require.isSet() and not require in invalidElements:
                        invalidElements.append(require)
        else:
            for require in requires[modeStr]:
                # Check whether all of the datasets required by this mode are set
                if not require.isSet() and not require in invalidElements:
                    invalidElements.append(require)
        return invalidElements

