"""
     qtgui/MGToolBar.py: CCP4MG Molecular Graphics Program
     Copyright (C) 2001-2008 University of York, CCLRC
     Copyright (C) 2009 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 PyQt4 import QtCore, QtGui
import guiUtils, MGSimpleDialog

class MGToolBar(QtGui.QToolBar):
  
  style_labels = { 'text_only' : "Text only",
               'icon_only' : "Icon only",
               'text_under' : "Text under icon",
               'text_beside' : "Text beside icon" }
  style_flags  = { 'text_only' : QtCore.Qt.ToolButtonTextOnly,
               'icon_only' : QtCore.Qt.ToolButtonIconOnly,
               'text_under' : QtCore.Qt.ToolButtonTextUnderIcon,
               'text_beside' : QtCore.Qt.ToolButtonTextBesideIcon }
  icon_size_menu = { 'small' : 16,
                 'medium' : 24,
                 'large' : 32 }

  def __init__(self,parent=None,title='',params={},supported_actions = [],default_actions=[]):
    QtGui.QToolBar.__init__(self,title,parent)
    self.supported_actions = supported_actions
    self.icon_size = 'medium'
    self.loaded_actions = []
    # Default loaded actions - probably overruled by params
    if not params.has_key('loaded_actions'):
      self.loadActions(default_actions)
    if params: self.setParams(params)
    self.setAcceptDrops(1)

  def contextMenuEvent(self,event):
      menu = QtGui.QMenu(self)
      menudef = self.getGuiDef('context')
      if menudef:
          guiUtils.populateMenu(self,menu,menudef,self.getActionDef)

      # The stuff for QWhatsThis
      menu.addSeparator()
      import functools
      whatsthis = menu.addAction(self.tr("What's this?"))
      self.connect(whatsthis,QtCore.SIGNAL("triggered(bool)"),functools.partial(QtGui.QWhatsThis.showText,self.mapToGlobal(event.pos()),self.tr("A toolbar for placing commonly used items with ccp4mg.")))

      menu.exec_(self.mapToGlobal(event.pos()))
      #menu.exec_()

  def dropEvent(self,event):
    #print "ToolBar.dropEvent"
    event.ignore()

  def getGuiDef(self,name='context'):
    return ['toggle_toolbar','sep','toolbar_text_only','toolbar_icon_only','toolbar_text_under','toolbar_text_beside',['Icon size','toolbar_icon_size_small','toolbar_icon_size_medium','toolbar_icon_size_large'],'sep','customise']


  def getActionDef(self,name=''):

    if name == 'toggle_toolbar':
      return dict ( text = 'Show/hide toolbar',
                    action = self.toggleViewAction() )
    
    if name == 'customise':
      return dict ( text = 'Customise..',
                    slot = self.customise,
                    toolTip = 'Select actions on menu' )


    # style options
    if MGToolBar.style_labels.has_key(name[8:]):
      name = name[8:]
      checked = self.toolButtonStyle()==MGToolBar.style_flags[name]
      return dict ( 
        text = MGToolBar.style_labels[name],
        group = 'toolbar_button_style',
        checkable = 1,
        checked = checked,
        slot = guiUtils.partial(self.setToolButtonStyle ,(MGToolBar.style_flags[name]))
      )

    # size options
    if name[0:17] == 'toolbar_icon_size':
       return dict ( 
        text = name[18:],
        group = 'toolbar_icon_size',
        checkable = 1,
        checked = name[18:] == self.icon_size,
        slot = guiUtils.partial(self.set_icon_size ,(name[18:]))
      )

    return self.parent().getActionDef(name=name)


  def set_icon_size(self,size=''):
    isize = MGToolBar.icon_size_menu[size]
    self.icon_size = size
    iconSize = QtCore.QSize(isize,isize)
    self.setIconSize(iconSize)

  def getParams(self):
    pars = {}
    pars['toolbar_icon_size'] = self.icon_size
    pars['toolbar_style'] = 'text_under'
    istyle = self.toolButtonStyle()
    for key,value in MGToolBar.style_flags.items():
      if value == istyle: pars['toolbar_style'] = key
    pars['toolbar_loaded_actions'] = []
    pars['toolbar_loaded_actions'].extend(self.loaded_actions)
    return pars

  def setParams(self,params={},**kw):
    params.update(kw)
    if params.has_key('toolbar_icon_size'):
      self.set_icon_size(params['toolbar_icon_size'])
    if params.has_key('toolbar_style') and MGToolBar.style_flags.has_key(params['toolbar_style']):
      self.setToolButtonStyle(MGToolBar.style_flags[params['toolbar_style']])

    if params.has_key('toolbar_loaded_actions'):
      self.loadActions(params['toolbar_loaded_actions'])

  def updateToolBar(self):
      self.clear()
      for act in self.loaded_actions:
        action = self.parent().findChild(QtGui.QAction,act)
        if action:
          self.addAction(action)

  def loadActions(self,action_list=[]):
      self.clear()
      self.loaded_actions=[]
      for name in action_list:
        action = self.parent().findChild(QtGui.QAction,name)
        if not action: action = guiUtils.createAction(name,self.parent())
        if action:
          self.addAction(action)
          self.loaded_actions.append(name)

  def mgAddAction(self,name,icon_path=''):
    if not self.loaded_actions.count(name):
      action = self.parent().findChild(QtGui.QAction,name)
      if not action:
        action = guiUtils.createAction(name,self.parent(),icon_path=icon_path)
      if action:
         self.addAction(action)
         self.loaded_actions.append(name)

  def mgRemoveAction(self,name):
    if self.loaded_actions.count(name):
      self.loaded_actions.remove(name)
      action = self.parent().findChild(QtGui.QAction,name)
      self.removeAction(action)
      
  def customise(self):

    if not hasattr(self,'customiseGui'):
      self.customiseGui = MGSimpleDialog.MGSimpleDialog(self)
      self.customiseGui.setWindowTitle('Select Toolbar Tools')
      self.customiseGui.setMinimumHeight(200)
      layout = QtGui.QVBoxLayout()
      self.action_list = QtGui.QListWidget(self)
      self.action_list.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
      # !!! This assumes all actions from the same class
      import os
      for name in self.supported_actions:
        adef = self.getActionDef(name=name)
        if adef:
          if adef.has_key('icon_path') and adef['icon_path'] != '':
            icon = guiUtils.createIcon(name,adef,icon_path=adef['icon_path'])
          else:
            icon = guiUtils.createIcon(name,adef,default_icon=None)
          if icon:
            item = QtGui.QListWidgetItem(
              icon,
              QtCore.QString(adef['text']),self.action_list)
          else:
             item = QtGui.QListWidgetItem(
              QtCore.QString(adef['text']),self.action_list)
          item.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsEnabled)
          item.setData(QtCore.Qt.UserRole,QtCore.QVariant(name))
          self.action_list.addItem(item)
          #if self.loaded_actions.count(name):item.setSelected(1)
          if self.loaded_actions.count(name):
            item.setCheckState(QtCore.Qt.Checked)
          else:
            item.setCheckState(QtCore.Qt.Unchecked)
      
      layout.addWidget(self.action_list)
      self.customiseGui.setLayout(layout)
      self.connect(self.action_list,QtCore.SIGNAL("itemClicked(QListWidgetItem *)"),self.handleCustomise)

    self.customiseGui.show()
    self.customiseGui.raise_()

  def handleCustomise(self,item=''):
    name = str(item.data(QtCore.Qt.UserRole).toString())
    #print "editToolBar",item,name
    if item.checkState() == QtCore.Qt.Checked:
       self.mgAddAction(name)
    else:     
       self.mgRemoveAction(name)
    


  
