"""
     python/ui/global_definitions.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     Copyright (C) 2009-2011 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.
"""
statusBarMessages = [""]
pluginsParams = {}

def VW(name):
  import view
  if view.CView.names.count(name) <= 0:
    v = view.CView('mainview')
  i = view.CView.names.index(name)
  return view.CView.insts[i]

def MGGUI():
  import GUI
  if not GUI.GUI.insts: GUI.GUI()
  return GUI.GUI.insts


def PICKLABEL():
  import atom_picking
  if not atom_picking.picklabels.insts: pl = atom_picking.picklabels()
  return atom_picking.picklabels.insts


def PD():
  return PICTUREDEFINITION()

def PICTUREDEFINITION():
  import picture_definition
  if not picture_definition.picture_definition.insts:
    pd = picture_definition.picture_definition()
  return picture_definition.picture_definition.insts

def MGCOLOUR():
  return CL()

def CL():
  import COLOUR
  if not COLOUR.COLOUR.insts: COLOUR.COLOUR()
  return COLOUR.COLOUR.insts

def HISTORY():
  import history
  if not history.CHistory.insts:
    history.CHistory()
  return history.CHistory.insts

def EDITHISTORY():
  import EditHistory
  if not EditHistory.EditHistoryManager.insts:
    eh = EditHistory.EditHistoryManager()
  return EditHistory.EditHistoryManager.insts

def WEB():
  import web
  if not web.web.insts: web.web()
  return web.web.insts

def CCP4DATABASE():
  import ccp4i_database
  if not ccp4i_database.ccp4i_database.insts:
    ccp4i_database.ccp4i_database()
  return ccp4i_database.ccp4i_database.insts

def RESOURCES():
  import MainLoopContainer
  return MainLoopContainer.MainLoopContainer.get(0).resources

def MODELINFO():
  import ModelInfo
  if not ModelInfo.ModelInfo.insts:
    ModelInfo.ModelInfo()
  return ModelInfo.ModelInfo.insts

def BUILD():
  import build
  if not build.build.insts:
    import COLOUR,dummyMG
    if not COLOUR.COLOUR.insts: c = COLOUR.COLOUR()
    #GRAPHICS_thread = dummyMG.GLUTThread()
    GRAPHICS_thread = None
    b = build.build(GRAPHICS_thread)
  return build.build.insts

def UPDATEDISPLAY(auto_save=1,target=None,controllingWidget=None):
  import rebuild
  rebuild.UpdateDisplay(auto_save=auto_save,target=target,controllingWidget=controllingWidget)
  
def PICTUREWIZARD():
  import picture_wizard
  if not picture_wizard.picture_wizard.insts:
    pw = picture_wizard.picture_wizard()
  return picture_wizard.picture_wizard.insts


def CRYSTALMANAGER():
  objlist = get_dataobj(object_type='CrystalData')
  if not objlist:
    import Crystal  
    xtl_data = Crystal.CrystalData(name='CrystalData')
    #print "CRYSTALMANAGER",xtl_data
  return  get_dataobj(object_type='CrystalData')[0]

def GL2DMANAGER():
  import Legend
  print "in GL2DMANAGER",Legend.GL2dScreen.insts
  if not Legend.GL2dScreen.insts or len(get_dataobj())==0: screen = Legend.GL2dScreen(name='Legends&Images')
  return Legend.GL2dScreen.insts[0]


#-----------------------------------------------------------------------
def PM_MANAGER():
#-----------------------------------------------------------------------
  import services
  if not services.ParamsManagerManager.insts:
    pmm = services.ParamsManagerManager()
  return services.ParamsManagerManager.insts
    
#-----------------------------------------------------------------------
def PM(name='',creator=None):
#-----------------------------------------------------------------------
  import services

  if name == 'all':
    return  services.ParamsManager.insts
  
  for i in services.ParamsManager.insts:
    #if i.name == name and name == 'movie_preferences': print 'PM existing'
    if i.name == name: return i

  # Is it existing ColourSchemeManager
  for i in services.ColourSchemeManager.insts:
    if i.name == name: return i

  # Is it a known ColourSchemeManager that can be recreated?
  if services.ColourSchemeManager.colour_pref_alias.count(name):
    #print "PM creating",name
    pm = services.ColourSchemeManager(name=name)
    return pm

  pm = None

    
  if name == 'HBond_param':
    import HBonds
    pm = HBonds.HBondsParamsManager()
  elif name == 'Contacts_param':
    import Contacts
    pm = Contacts.ContactsParamsManager()
  elif name == 'SecStr_param':
    import model
    pm = model.SecStructureParamsManager()
  elif name == 'model_drawing_style':
    import model
    pm = model.createDrawingStylePM(name=name)
  elif name == 'stereo_prefs':
    import MGGLWidget
    pm = MGGLWidget.createStereoParamsManager()
  elif name == 'ambient_occlusion_prefs':
    import MGGLWidget
    pm = MGGLWidget.createAOParamsManager()
  elif name == 'miscell_prefs':
    import MGGLWidget
    pm = MGGLWidget.createMiscParamsManager()
  elif name == 'render_quality':
    import model
    pm = model.createRenderParamsManager()
  elif name == 'SASArea_param':
    import model
    pm = model.createSASAreaPM(name=name)

  elif name == 'MapDispParamsManager':
    import map
    pm =map.createDrawingStylePM(name=name)

  elif name == 'surface_drawing_style':
    import SurfaceDispobj
    pm = SurfaceDispobj.createDrawingStylePM(name=name)
  elif name == 'HBond_drawing_style':
    import HBonds
    pm = HBonds.createDrawingStylePM(name=name)


  elif name == 'screenshot_preferences':
    import screenshot
    if not screenshot.PREFERENCES:
      screenshot.PREFERENCES = screenshot.create_screenshot_preferences()
    pm = screenshot.PREFERENCES
    
  elif name == 'movie_preferences':
    #print 'PM creating movie_preferences'
    import presentation
    if not presentation.movie_preferences.insts:
       presentation.movie_preferences()
    pm = presentation.movie_preferences.insts.movie_preferences()
    
  elif name == 'save_session_options':
    import history
    pm = history.createParamsManager()
    
  elif name == 'Surface_electro':
    import SurfaceDispobj
    pm = SurfaceDispobj.createElectroParamsManager()
    
  elif name == 'Animation_param':
    import Animation
    pm = Animation.AnimationParamsManager()
    
  elif name == 'atom_label_params':
    import MolLabel
    pm = MolLabel.atomLabelParamsManager()

  elif name == 'download_preferences':
    import downloadPdb
    pm = downloadPdb.createDownloadPM()
    
  elif name == 'annotation_format':
    import Annotation
    pm = Annotation.createAnnotationParamsManager()
    
  elif name == 'advanced_options':
    import MGMainWindow
    pm = MGMainWindow.createAdvancedParamsManager()

  elif name == 'centre_mode':
    import MGMainWindow
    pm = MGMainWindow.createRecentreParamsManager()

  else:
    if pluginsParams.has_key(name):
	return pluginsParams[name]
    else:  
      if creator:
        pm = creator()
        pluginsParams[name] = pm
    
  return pm

#-------------------------------------------------------------------
def data( name ):
#-------------------------------------------------------------------
  import dataobj
  if dataobj.DataObj.dataobj_names.count(name) <= 0:
    #print "NO MOLDATA current names:", MolData.names
    if name == 'Legends&Images':
      return GL2DMANAGER()
    else:
      return ""
  else:
    i = dataobj.DataObj.dataobj_names.index(name)
    #print "MOLDATA OK ",name
    return dataobj.DataObj.dataobj_insts[i]

#------------------------------------------------------------------
def disp(parent,name):
#------------------------------------------------------------------
  m = data(parent)
  if not m: return None
  if m.objnames.count(name) <= 0:
    return None
  else:
    i = m.objnames.index(name)
    return m.objinsts[i]

#-----------------------------------------------------------------
def get_dataobj (name='',object_type='',mode='all',PCAtom=None ):
#-----------------------------------------------------------------
  import dataobj
  ret = []
  if PCAtom:
    import mmut
    theAddr= mmut.GetMMANManagerAddress(PCAtom)
    if theAddr != "":
      for obj in dataobj.DataObj.dataobj_insts:
        if obj.object_type == 'MolData':
          if theAddr == obj.molHnd.GetAddress():
            ret.append(obj)
  elif name == 'CrystalData':
    return [CRYSTALMANAGER()]
  elif name:
    if dataobj.DataObj.dataobj_names.count(name):
      ret.append(dataobj.DataObj.dataobj_insts [ dataobj.DataObj.dataobj_names.index(name)])
  else:
    for obj in dataobj.DataObj.dataobj_insts:
      if not object_type or obj.object_type == object_type:
        ret.append(obj)
        if mode == 'first': return ret
  return ret

#--------------------------------------------------------------------
def get_dispobj(object_type=[],mode='all',name='',graphics_object=None):
#--------------------------------------------------------------------
  import dataobj,types
  import Legend
  if Legend.GL2dScreen.insts and not Legend.GL2dScreen.insts[0] in dataobj.DataObj.dataobj_insts:
    dataobj.DataObj.dataobj_insts.append(Legend.GL2dScreen.insts[0])
  if Legend.GL2dScreen.insts and not Legend.GL2dScreen.insts[0].name in dataobj.DataObj.dataobj_names:
    dataobj.DataObj.dataobj_names.append(Legend.GL2dScreen.insts[0].name)
     
  if isinstance(object_type,types.StringType):
    if object_type == '':
      object_type=[]
    else:
      object_type = [object_type]
  if name:
    for da in dataobj.DataObj.dataobj_insts:
      if da.objnames.count(name):
        return da.objinsts[da.objnames.index(name)]
    # Found nothing with that name 
    return ''
  elif graphics_object:
    #print "global_definitions.get_dispobj graphics_object",graphics_object
    for da in dataobj.DataObj.dataobj_insts:
      for obj in da.objinsts:
        #print "global_definitions.get_dispobj obj", obj.graphmod
        if obj.graphmod == graphics_object:
          return [obj]
    return []
  else:
    ret = []
    for da in dataobj.DataObj.dataobj_insts:
      for obj in da.objinsts:
        if not object_type or object_type.count(obj.object_type):
          ret.append(obj)
          if mode == 'first': return ret
    return ret

#-------------------------------------------------------------
def Appl (name='',mode='one'):
#-------------------------------------------------------------
  import Application
  
  if name == 'Superpose':
    import Superpose
    if Superpose.Superpose.insts:
      return Superpose.Superpose.insts
    else:
      return Superpose.Superpose()
  
  #print " Appl",name,Application.Application.application_names
  if Application.Application.application_names.count(name):
    i = Application.Application.application_names.index(name)
    return Application.Application.application_insts[i]

    
  return None

#----------------------------------------------------------------
def Presentation(name):
#----------------------------------------------------------------
  import presentation
  #print "global_definitions",name
  for obj in presentation.presentation.insts:
    #print "global_definitions Presentation obj",obj, obj.identifier
    if name == obj.identifier:  return obj
  return None

#----------------------------------------------------------------
def PictureHandler(name):
#----------------------------------------------------------------  
  import picture_wizard
  if picture_wizard.PictureHandler.insts.has_key(name):
    return  picture_wizard.PictureHandler.insts[name]
  else:
    return None


def DEVELOPER():
  import os
  if os.environ.has_key("DEVELOPER"):
     return 1
  if PM('advanced_options').getparams()['developer_mode']:
     return 1
  return 0

def GLWIDGETS():
  return MAINWINDOW().glWidgets

def MAINWINDOW():
  import MGApplication
  return MGApplication.GetMainWindow()

def MGAPPLICATION():
  import MGApplication
  return MGApplication.QtApp()

def PREFERENCESWINDOW():
  MAINWINDOW().handlePreferences()
  return MAINWINDOW().wPreferences

def JOBCONTROL():
  return MAINWINDOW().jobControl

def DISPLAYTABLE():
  if not hasattr(MAINWINDOW(),"MGDisplayTable"): return None
  return  MAINWINDOW().MGDisplayTable

def FONTMANAGER():
  import FontManager
  if not FontManager.FontManager.insts:
    FontManager.FontManager()
  return FontManager.FontManager.insts


def FILEVIEWER(name='',title='CCP4mg Data Listing'):
  import mgFileViewer
  if hasattr(MAINWINDOW(),"fileViewer"):
    viewer = MAINWINDOW().fileViewer
  else:
    viewer = mgFileViewer.mgFileViewer(name=name,title=title)
    MAINWINDOW().fileViewer = viewer
  viewer.show()
  viewer.raise_()
  """
  viewer = MAINWINDOW().findChild(mgFileViewer.mgFileViewer,name)
  if not viewer:
    viewer = mgFileViewer.mgFileViewer(name=name,title=title)
  else:
    viewer.show()
  """
  return viewer

def GRAPHVIEWER(title='CCP4mg Data Listing'):
  if hasattr(MAINWINDOW(),"graphViewer"):
    viewer = MAINWINDOW().graphViewer
  else:
    import MGQTmatplotlib
    viewer = MGQTmatplotlib.LogGraph()
    viewer.showActionBar()
    MAINWINDOW().graphViewer = viewer
  return viewer

def HELPBROWSER():
  return MAINWINDOW().getHelpBrowser()
