"""
     qtgui/ccp4iGui.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 QtGui,QtCore
from global_definitions import *



def openGui():
  if not ccp4iAliasGui.insts:
    ccp4iAliasGui.insts = ccp4iAliasGui(MAINWINDOW())

  if not ccp4iAliasGui.insts.isVisible():
    ccp4iAliasGui.insts.loadAliases()
    ccp4iAliasGui.insts.show()
  else:
    ccp4iAliasGui.insts.raise_()

class ccp4iAliasGui(QtGui.QDialog):

  insts = None

  def __init__(self,parent=None):
    QtGui.QDialog.__init__(self,parent)
    
    layout = QtGui.QVBoxLayout()
    
    line_layout = QtGui.QHBoxLayout()
    line_layout.addWidget(QtGui.QLabel('In CCP4mg you can add and change CCP4i directory aliases.',self))
    line_layout.addWidget(QtGui.QLabel('Please user CCP4i to change project directories.',self))
    layout.addLayout(line_layout)

    grid_layout =  QtGui.QGridLayout()
    grid_layout.addWidget(QtGui.QLabel('Alias',self),0,0,1,1)
    #self.alias = QtGui.QLineEdit(self)
    self.alias = QtGui.QComboBox(self)
    self.alias.setEditable(1)
    self.alias.setToolTip('Choose a directory alias to edit or enter a new one')

    grid_layout.addWidget(self.alias,1,0,1,1)

    grid_layout.addWidget(QtGui.QLabel('Directory path',self),0,1,1,1)
    self.path =  QtGui.QLineEdit(self)
    self.path.setMinimumWidth(200)
    self.path.setToolTip('Choose a directory to be linked to the alias')
    grid_layout.addWidget(self.path,1,1,1,1)

    browser = QtGui.QPushButton('Browser',self)
    browser.setToolTip('Use browser to find directory')
    self.connect(browser,QtCore.SIGNAL('clicked()'),self.openBrowser)
    grid_layout.addWidget(browser,1,2,1,1)
    layout.addLayout(grid_layout)

    dialog = QtGui.QDialogButtonBox(self)
    button = dialog.addButton(QtGui.QDialogButtonBox.Help)
    self.connect(button,QtCore.SIGNAL('clicked()'),self.help)
    button = dialog.addButton(QtGui.QDialogButtonBox.Apply)
    self.connect(button,QtCore.SIGNAL('clicked()'),self.Apply)
    button.setToolTip('Save the current alias and directory path')
    button = dialog.addButton(QtGui.QDialogButtonBox.Cancel)
    self.connect(button,QtCore.SIGNAL('clicked()'),self.close)
    button.setToolTip('Close window without saving any changes')
    button = dialog.addButton('Remove alias',QtGui.QDialogButtonBox.ActionRole)
    self.connect(button,QtCore.SIGNAL('clicked()'),self.deleteAlias)
    button.setToolTip('Remove the current alias from the directory database - does NOT delete the directory')

    self.connect(self.alias,QtCore.SIGNAL('currentIndexChanged(int)'),self.changedAlias)

    
    layout.addWidget(dialog)
    self.setLayout(layout)

  def loadAliases(self):
    self.alias.clear()
    projects,aliases = CCP4DATABASE().getProjectsList(projects=0,aliases=1)
    #print 'ccp4iAliasGui projects',projects
    #self.alias.addItem('')
    #for proj in projects: self.alias.addItem(proj)
    #self.alias.addItem(' -- ')
    for proj in aliases: self.alias.addItem(proj)
    
    self.path.setText('')

  def changedAlias(self,iAlias):
    print 'changedAlias',iAlias,self.path
    if iAlias == 0:
      self.path.setText('')
    else:
      new_path = CCP4DATABASE().get_project_dir(str(self.alias.currentText()))
      #print 'changedAlias new_path',new_path
      if new_path: self.path.setText(new_path)

  def deleteAlias(self):
    alias = str(self.alias.currentText())
    if not alias:
      QtGui.QMessageBox.warning(self,'Error removing directory alias','No directory alias is given')
      return
    if not CCP4DATABASE().get_project_dir(alias):
      QtGui.QMessageBox.warning(self,'Error removing directory alias',alias+' is not saved in the directories database')
      return
    rv = CCP4DATABASE().delete_alias(alias)
    if rv[0]:
      #print 'deleteAlias rv',rv
      QtGui.QMessageBox.warning(self,'Error removing directory alias',rv[1])
      return
    
    rv = CCP4DATABASE().write_ccp4i_directories()
    if rv[0]:
       QtGui.QMessageBox.warning(self,'Error creating directory alias',rv[1])
       return
    self.loadAliases()

  def help(self):
    HELPBROWSER().loadMgHelp(file='projects.html')

  def Apply(self):
    alias = str(self.alias.currentText())
    if not alias:
      QtGui.QMessageBox.warning(self,'Error creating directory alias','No directory alias is given')
      return
    path = str(self.path.text())
    import os
    if not os.path.exists(path):
      QtGui.QMessageBox.warning(self,'Error creating directory alias','Directory path is not valid')
      return
    rv = CCP4DATABASE().edit_dir_alias(alias,path)
    if rv[0]:
      #print 'Apply rv',rv
      QtGui.QMessageBox.warning(self,'Error creating directory alias',rv[1])
      return
    
    rv = CCP4DATABASE().write_ccp4i_directories()
    if rv[0]:
       QtGui.QMessageBox.warning(self,'Error creating directory alias',rv[1])
       return

    self.close()
    
    
  def openBrowser(self):
    self.browser = QtGui.QFileDialog(self)
    self.browser.setFileMode(QtGui.QFileDialog.Directory)
    self.browser.setWindowTitle('Directory with CCP4i alias '+str(self.alias.currentText()))
    self.browser.setModal(True)
    self.connect(self.browser, QtCore.SIGNAL('filesSelected (const QStringList&)'), self.handleBrowser)
    self.browser.show()

  def handleBrowser(self,dirn):
    #print 'handleBrowser',dirn
    import os
    if dirn:
      dirn = str(dirn[0])
      if os.path.exists(dirn) and os.path.isdir(dirn):
        self.path.setText(dirn)
        self.browser.close()
        return
      
    self.browser.close()
    self.path.setText('')
    return
