"""
     python/ui/atom_picking.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 cprim
from atom_util import *
from mmdb2 import *
import keys
from global_definitions import *
from dataobj import data
from dataobj import get_dispobj
from keys import *


#------------------------------------------------------------------
#------------------------------------------------------------------
#------------------------------------------------------------------
class picklabels:
#------------------------------------------------------------------
#------------------------------------------------------------------
#------------------------------------------------------------------

  insts = ''
  initialisation = { 'label_style' : [0,0,0,1,1,1,1,0,0,0,0,0,0,0,0],
                     'max_labels' : 20,
                     'truncate_mol_name' : 0,
                     'truncate_mol_name_length' : 6 }
  
  mapping = [ [],[],[1],[2],[3,4],[5],[6,7],[8],[10],[11],[13],[15],[17],[],[]]
  
  def __init__(self,**kw):
    picklabels.insts= self
    for key,value in picklabels.initialisation.items():
      setattr(self,key,value)
    self.setparams(params=kw)
    #Maintain list of labels - each item is [display_object,label_id,PCAtom]
    self.label_ids = []
    self.uid_counter = 1
    


#-----------------------------------------------------------------------
  def addLabel(self,pickevent=None,atm_ptr=None,dispobj=None):
#-----------------------------------------------------------------------
    #print "PICKLABEL.addLabel",pickevent
    matrix = None
    if pickevent:
       atm_ptr = pickevent.getPickedAtoms()[0]
       dispobj = pickevent.getDispObj()
       if hasattr(pickevent,"transMat"):
         matrix = pickevent.transMat
       #print "atm_ptr,dispobj",atm_ptr,dispobj
    if not atm_ptr or not dispobj: return 0

    '''
    # Check not already on list of labelled atoms
    for label_id in self.label_ids:
      if repr(label_id[2]) == repr(atm_ptr):
        return label_id[1]
    '''

    self.uid_counter = self.uid_counter + 1
    rv = dispobj.addPickedAtom(self.uid_counter,atm_ptr,matrix=matrix)
    if rv:
      self.label_ids = [x for x in self.label_ids if x[0] != rv]
      return 1
    self.label_ids.append([self.uid_counter,dispobj.name])

    self.clear_labels()
    return 1

    
#-----------------------------------------------------------------------
  def clear_labels(self,max_labels=-1):
#-----------------------------------------------------------------------
    if max_labels<0: max_labels = self.max_labels
    while len(self.label_ids)>max_labels:
      uid,dispobj_name = self.label_ids.pop(0)
      obj = get_dispobj(name=dispobj_name)
      if obj: obj.removePickedAtom(uid)
      
  
#-----------------------------------------------------------------------
  def getAtomLabel(self,atm_ptr=None,molobj=None,label_style=[]):
#-----------------------------------------------------------------------
    import dataobj

    #print "getAtomLabel label_style",self.label_style, atm_ptr

    if not molobj:
      molobj = get_dataobj(PCAtom=atm_ptr)
      #print molobj
      if not molobj:return "No object"
      molobj = molobj[0]

    if not label_style: label_style = self.label_style
    
    mask = inta(20)
    for j in range(0,20): mask[j] = 0
    for j in range(0,len(label_style)):
      if label_style[j]:
        for k in picklabels.mapping[j]: mask[k] = 1
    text_label = molobj.molHnd.AtomLabel(atm_ptr,mask)

    if label_style[13] or label_style[14]:
      model = atm_ptr.GetModelNum()
      symid = molobj.model_symmetry.modelSymid(model)
      if symid:
        if label_style[13]:
          # symid
          text_label = symid + ' ' + text_label
        if label_style[14]:
          #symop
          symop = molobj.model_symmetry.modelSymop(model)
          text_label = symop + ' ' + text_label
    
    if label_style[1]:
      if self.truncate_mol_name:
        moln = molobj.name_label[0:min(self.truncate_mol_name_length,len(molobj.name_label))]
      else:
        moln = molobj.name_label
      text_label=moln+':'+text_label
    if label_style[0]:
      text_label = str(molobj.MolData_number)+')'+text_label


    #print " draw_atom_label",text_label
    return text_label


#------------------------------------------------------------------
  def getparams(self):
#------------------------------------------------------------------
    lab = {}
    for key in picklabels.initialisation.keys():
      lab[key] = getattr(self,key,'')
    return lab

#-----------------------------------------------------------------------
  def setparams(self,params={}):
#-----------------------------------------------------------------------
    #print "picklabels.setparams",params
    # Check the type of params - avoid problems updating from pre v2
    for key in picklabels.initialisation.keys():
      if params.has_key(key) and type(params[key])==type(picklabels.initialisation[key]): setattr(self,key,params[key])

    if len(self.label_style)< len(picklabels.initialisation['label_style']):
      self.label_style.extend(picklabels.initialisation['label_style'][len( self.label_style):])

