"""
     python/ui/MapPlane.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     Copyright (C) 2009-2010 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 mmut import getPCAtom
import map, pygl_coord
from global_definitions import *

class MapPlane:
  plane_mode_menu = ['through selected atoms','parallel to crystal face','specifying plane']
  plane_mode_alias = ['selection','crystal_face','plane']
  selection_mode_menu = ['all atoms',
                         'atom 1 & atom 2',
                         'atom 1 & atom 3',
                         'atom 2 & atom 3',
                         '1, perpendicular 2->3',
                         '1, parallel 2->3',
                         '2, perpendicular 1->3',
                         '2, parallel 1->3',
                         '3, perpendicular 1->2',
                         '3, parallel 1->2']
  selection_mode_alias = ['thru_all',
                         'thru_12',
                         'thru_13',
                         'thru_23',
                         'thru_1_perp_23',
                         'thru_1_paral_23',
                         'thru_2_perp_13',
                         'thru_2_paral_13',
                         'thru_3_perp_12',
                         'thru_3_paral_12']
  faces_alias_menu = ['AB','AC','BC']
  faces_menu = [' ab face',' ac face',' bc face']
  initialisation = { 'plane_mode' : 'plane',
                               'selection_mode' :'thru_all', 
                               'selection1' : [],
                               'selection2' : [],
                               'selection3' : [],
                               'specify_plane_A' : 1,
                               'specify_plane_B' : 0,
                               'specify_plane_C' : 0,
                               'specify_plane_D' : 0,
                               'crystal' : '',
                               'crystal_face' : 'AB',
                               'contour_spacing' : 1.0,
                               'set_camera' : 0,
                               'raise_plane' : 0.0 }
  initialisation_order = ['plane_mode', 'selection_mode','MolData','selection1', 'selection2','selection3','specify_plane_A', 'specify_plane_B','specify_plane_C' , 'specify_plane_D','crystal','crystal_face','contour_spacing','raise_plane' ]
  absolute_contour_spacing = 1.0
  sigma_contour_spacing = 0.25

  
  def __init__(self,params={}):

    for key,value in MapPlane.initialisation.items():
      setattr(self,key,value)
    self.set_params(params)
    self.update_plane()


  def set_params(self,params):

    for key,value in params.items():
      if MapPlane.initialisation.has_key(key):
        setattr(self,key,value)
          

  def params(self,all=1):
    #print "params",self.plane_definition
    pars = {}
    if all:
      for key in MapPlane.initialisation.keys():
        pars[key] = getattr(self,key)
    else:
      for key,deft in MapPlane.initialisation.items():
        value = getattr(self,key)
        if deft != value: pars[key] = value
    return pars

  def update_plane(self):

    import pygl_coord
    plane = None
    
    if self.plane_mode == 'plane':
      
	plane = pygl_coord.Plane(self.specify_plane_A,self.specify_plane_B,self.specify_plane_C,self.specify_plane_D)
        plane.Normalize()
        orig_D = plane.get_D()
        new_D = orig_D + self.raise_plane
        plane.set_D(new_D)
	#print plane.get_A(),plane.get_B(),plane.get_C(),plane.get_D()
        
    elif  self.plane_mode == "selection":
	#print "Through atoms"
        cart1 = None
        cart2 = None
        cart3 = None
        # selection is [MolData.name,atomCID]
        if self.selection1:
          molobj = get_dataobj(self.selection1[0])
          if molobj:
	    atm_ptr = molobj[0].interpretAtomID(molobj[0],self.selection1[1])
            if atm_ptr: cart1 = pygl_coord.Cartesian(atm_ptr.x,atm_ptr.y,atm_ptr.z)
        if self.selection2:
          molobj = get_dataobj(self.selection2[0])
          if molobj:
	    atm_ptr = molobj[0].interpretAtomID(molobj[0],self.selection2[1])
            if atm_ptr: cart2 = pygl_coord.Cartesian(atm_ptr.x,atm_ptr.y,atm_ptr.z)
        if self.selection3:
          molobj = get_dataobj(self.selection3[0])
          if molobj:
	    atm_ptr = molobj[0].interpretAtomID(molobj[0],self.selection3[1])
            if atm_ptr: cart3 = pygl_coord.Cartesian(atm_ptr.x,atm_ptr.y,atm_ptr.z)

        #print "MapSlice.draw cart",cart1,cart2,cart3

        if self.selection_mode == 'thru_all':
	  pass
        elif self.selection_mode == 'thru_12':
          cross = pygl_coord.Cartesian.CrossProduct(cart1-cart3,cart2-cart3)
          cart3 = cart1 + cross
        elif self.selection_mode == 'thru_13':
          cross = pygl_coord.Cartesian.CrossProduct(cart1-cart2,cart3-cart2)
          cart2 = cart1 + cross
        elif self.selection_mode == 'thru_23':
          cross = pygl_coord.Cartesian.CrossProduct(cart2-cart1,cart3-cart1)
          cart1 = cart2 + cross
        elif self.selection_mode =='thru_1_perp_23':
          up = pygl_coord.Cartesian.CrossProduct(cart1-cart2,cart1-cart3)
          up.normalize()
          forward = cart1-pygl_coord.Cartesian.MidPoint(cart2,cart3)
          forward.normalize()
          right = pygl_coord.Cartesian.CrossProduct(up,forward)
          cart2 = cart1 + up
          cart3 = cart1 + forward
        elif  self.selection_mode == 'thru_1_paral_23':
          up = pygl_coord.Cartesian.CrossProduct(cart1-cart2,cart1-cart3)
          up.normalize()
          forward = cart1-pygl_coord.Cartesian.MidPoint(cart2,cart3)
          forward.normalize()
          right = pygl_coord.Cartesian.CrossProduct(up,forward)
          cart2 = cart1 + up
          cart3 = cart1 + right
        elif self.selection_mode =='thru_2_perp_13':
          up = pygl_coord.Cartesian.CrossProduct(cart2-cart1,cart2-cart3)
          up.normalize()
          forward = cart2-pygl_coord.Cartesian.MidPoint(cart1,cart3)
          forward.normalize()
          right = pygl_coord.Cartesian.CrossProduct(up,forward)
          cart1 = cart2 + up
          cart3 = cart2 + forward
        elif self.selection_mode == 'thru_2_paral_13':
          up = pygl_coord.Cartesian.CrossProduct(cart2-cart1,cart2-cart3)
          up.normalize()
          forward = cart2-pygl_coord.Cartesian.MidPoint(cart1,cart3)
          forward.normalize()
          right = pygl_coord.Cartesian.CrossProduct(up,forward)
          cart1 = cart2 + up
          cart3 = cart2 + right
        elif self.selection_mode ==  'thru_3_perp_12':
          up = pygl_coord.Cartesian.CrossProduct(cart3-cart2,cart3-cart1)
          up.normalize()
          forward = cart3-pygl_coord.Cartesian.MidPoint(cart1,cart2)
          forward.normalize()
          right = pygl_coord.Cartesian.CrossProduct(up,forward)
          cart1 = cart3 + up
          cart2 = cart3 + forward
        elif self.selection_mode == 'thru_3_paral_12':
          up = pygl_coord.Cartesian.CrossProduct(cart3-cart2,cart3-cart1)
          up.normalize()
          forward = cart3-pygl_coord.Cartesian.MidPoint(cart1,cart2)
          forward.normalize()
          right = pygl_coord.Cartesian.CrossProduct(up,forward)
          cart1 = cart3 + up
          cart2 = cart3 + right
        plane = pygl_coord.Plane(cart1,cart2,cart3)
        plane.Normalize()
        orig_D = plane.get_D()
        new_D = orig_D + self.raise_plane
        plane.set_D(new_D)
	#print plane.get_A(),plane.get_B(),plane.get_C(),plane.get_D()

    elif self.plane_mode == 'crystal_face':
        face_map = { 'ab' : 'C',  'ac' : 'B', 'bc': 'A' }
        dataobj = get_dataobj(self.crystal)
        #print "crystal_face mode",self.crystal,dataobj
        if dataobj:
          obj_list = dataobj[0].get_dispobj()
          q = None
          ii = 0
          while (not q) and ii<len(obj_list):
            if obj_list[ii].graphmod:
              try:
                q = obj_list[ii].graphmod.obj.GetUnitCellAlignmentRotation(face_map[self.crystal_face])
              except:
                pass
            ii = ii+1
          if q:
            quat = q
            zaxis = pygl_coord.Cartesian(0,0,1)
            # 8/2/2010 quat fix, hopefully.
            norm = quat.getInvMatrix() * zaxis
            plane = pygl_coord.Plane(norm.get_x(),norm.get_y(),norm.get_z(),0)

    if plane: self.plane = plane
    self.setCamera()


  def setCamera(self,plane=None):
      if not plane: plane = self.plane
      #print plane, self.set_camera
      if plane and self.set_camera:
        import math        
        plane_norm = pygl_coord.Cartesian(plane.get_A(),plane.get_B(),plane.get_C())
        zaxis = pygl_coord.Cartesian(0.0, 0.0, 1.0);
        cross = zaxis.CrossProduct(plane_norm,zaxis);
        if abs(cross.get_x()*cross.get_x()+cross.get_y()*cross.get_y()+cross.get_z()*cross.get_z()>1.0e-6) :
          angle = math.acos(abs(plane.get_C()))
          if plane.get_C()>0.0: angle = -angle
          rotquat = pygl_coord.Quat(cross.get_x(),cross.get_y(),cross.get_z(),1,-angle*180.0/math.pi);
          MAINWINDOW().glWidget.setQuat(rotquat)
        else:
          rotquat = pygl_coord.Quat(0.0,0.0,0.0,0)
          MAINWINDOW().glWidget.setQuat(rotquat)


#------------------------------------------------------------------
  def plane_movie_interpolation(self,initial_status=[],final_status=[], \
                          fraction=0.0,step=0,**keywords):
#------------------------------------------------------------------
    # it would be nice if this did something to move plane in movies
    pass
