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

     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 dataobj, HBonds
from global_definitions import *
import cprim
 
 
class Contacts(HBonds.HB_Contacts,dataobj.DispObj):

  edit_make_vector = None
  edit_test_atomtype = 0
  #edge_popup = {
  #  'edit':['Contacts','Contacts.define_contacts_popup_menu'] }
  class_dependents = { } 
  
  def updateCrystal(self):
      dataobj.DispObj.updateCrystal(self)
      self.do_redraw = 2
  
#------------------------------------------------------------------
  def unthreadedDraw (self ):
#------------------------------------------------------------------
    pm = self.getDrawingStylePM()
    if pm.get('contacts_line_style')== 'cylinders':
       line_style=cprim.DASHCYLINDER
    else:
       line_style=cprim.DASHLINE
    label_mode = int(pm.get('contacts_label_mode'))
    line_width = int(pm.get('contacts_line_width'))
    self.unthreadedDraw_main(line_style,line_width,label_mode)

  def __init__(self,parent='',visible=1,name='', \
               selection='',colour='',style='', \
               params={},selparams={'command':'all'},styleparams={},colparams={},**keywords):

    pars = { 'selection' : '',
             'colour' : 'red',
             'style' : '' }
    pars.update(params)

    
    dataobj.DispObj.__init__(self,'Contacts',name,parent= parent, \
                     visible=visible, params=pars)


    HBonds.HB_Contacts.__init__(self,selparams=selparams,styleparams=styleparams,params=params,colparams=colparams)
    self.colour = 'red'
    import VectorsDispobj
    self.graphmod = VectorsDispobj.Vectorsgraphicsmodel()
    self.graphmod.ui = self
    BUILD().append(self.graphmod)
    self.CContact = None
    self.Connectivity2 = None
    
    self.saved_edits = []
        
    self.set_colour(colour=self.colour,force=1)
    
    PM('Contacts_param').add_dependent(self.set_do_redraw)
    self.update_dependents('create')
    
#------------------------------------------------------------------
  def delete(self,**keywords):
#------------------------------------------------------------------
    PM('Contacts_param').remove_dependent(self.set_do_redraw)    
    dataobj.DispObj.delete(self)
    HBonds.HB_Contacts.delete(self)


    if hasattr(self,'graphmod') and self.graphmod:
      BUILD().deletemod(self.graphmod)



    
#------------------------------------------------------------------
  def list_data ( self,filename='',overwrite='query',**keywords ):
#------------------------------------------------------------------
    if not self.CContact:
      if self.calculate(): return

    # Set up text to be listed
    text = "Close contacts between\nSet 1:" + \
           self.parent.filename[2] + "  ::  " + \
           self.SelHandle1.getLabel() +"\n" 
    if self.SelHandle1.getCommand() != self.SelHandle2.getCommand():
      text = text + "Set 2:" +  \
             self.parent.filename[2] + "  ::  " + \
             self.SelHandle2.getLabel() +"\n"
    text = text + "\n" + self.CContact.Print()

    if filename:
      import utils
      utils.saveFile(filename,text=text,warning=1,overwrite=overwrite)

    else:
      return text
    
   
#------------------------------------------------------------------------
  def calculate ( self ):
#------------------------------------------------------------------------
    if self.CContact: 
      del self.CContact
      self.CContact = None

    selHnd1 = self.SelHandle1.getSelHnd()
    selHnd2 = self.SelHandle2.getSelHnd()

    import mmut
    self.CContact = mmut.CContact(self.parent.molHnd,selHnd1, \
                             self.parent.molHnd,selHnd2)

    self.Connectivity2 = self.CContact.close_contacts
    pm = PM('Contacts_param')
    pm.update(self.CContact.SetParams)

    if self.parent.nmr_models:
      self.CContact.Calculate(True)
    else:
      self.CContact.Calculate(False)
    #print 'Contacts.calculate',self.SelHandle1.getNofAtoms(),self.SelHandle2.getNofAtoms(),self.Connectivity2.GetNofConnections()
    return 0

#--------------------------------------------------------------------------
def ContactsParamsManager( name='Contacts_param'):
#--------------------------------------------------------------------------
  import services

  def onChange(pmg):
    from PyQt4 import QtGui
    modeWidget =  pmg.findChild(QtGui.QWidget,'test_VDW_radius')
    simple_min_cutoff =  pmg.findChild(QtGui.QWidget,'simple_min_cutoff')
    simple_max_cutoff =  pmg.findChild(QtGui.QWidget,'simple_max_cutoff')
    VDW_fraction_min = pmg.findChild(QtGui.QWidget,'VDW_fraction_min')
    VDW_fraction_max = pmg.findChild(QtGui.QWidget,'VDW_fraction_max')
    if not modeWidget or not simple_min_cutoff or not simple_max_cutoff or not VDW_fraction_min or not VDW_fraction_max:
      return
    if not hasattr(modeWidget,"currentText") or not hasattr(simple_min_cutoff,"setEnabled") or not hasattr(simple_max_cutoff,"setEnabled"):
      return
    if modeWidget.currentText() == modeWidget.tr("fraction of v.d. Waals' radius"):
       simple_min_cutoff.setEnabled(False)
       simple_max_cutoff.setEnabled(False)
       VDW_fraction_min.setEnabled(True)
       VDW_fraction_max.setEnabled(True)
    else:
       simple_min_cutoff.setEnabled(True)
       simple_max_cutoff.setEnabled(True)
       VDW_fraction_min.setEnabled(False)
       VDW_fraction_max.setEnabled(False)

  return services.ParamsManager( name=name,
              title='Close Contacts',
              picture_definition = 1,
              onCreate=onChange,
              c_access = 1,
              help = 'analysis#contacts',                   
              gui=[  'test_VDW_radius',
                     'label_VDW_radius',
                     'exclude_hbondable',
                     'test_metal_coord_distance',
                             'simple_min_cutoff','simple_max_cutoff',
                             'VDW_fraction_min','VDW_fraction_max'],
              default = {'test_VDW_radius':0,
                         'label_VDW_radius': 0,
                         'exclude_hbondable' : 0,
                         'test_metal_coord_distance' : 1,
                         'simple_min_cutoff':0.0, 
                         'simple_max_cutoff':4.0, 
                         'VDW_fraction_min':0.0,
                         'VDW_fraction_max':0.9
                         },
              definition={'test_VDW_radius': dict(type='bool',label='Cutoff using',style='combobox',menu=['distance in angstroms','fraction of v.d. Waals\' radius'],alias=[0,1],onchange=onChange),
                          'label_VDW_radius':dict(type='bool',label='Label with fraction of VDW radius',style='checkbox'),
                          'exclude_hbondable':dict(type='bool',label='Exclude atom pairs that hydrogen bond',style='checkbox'),
                          'test_metal_coord_distance':dict(type='bool',label='Check metals coordination distance',style='checkbox'),
                         'simple_min_cutoff':dict(type=float,label='Simple min cutoff',style='spinbox',max=100.0,min=0.0,step=1.0), 
                         'simple_max_cutoff':dict(type=float,label='Simple max cutoff',style='spinbox',max=100.0,min=0.0,step=1.0),
                         'VDW_fraction_min':dict(type=float,label='Fraction of VDWs, min cutoff',style='spinbox',max=10.0,min=0.0,step=0.1),
                         'VDW_fraction_max':dict(type=float,label='Fraction of VDWs, max cutoff',style='spinbox',max=10.0,min=0.0,step=0.1)
                         })


