# -*- coding: utf-8 -*-

# Copyright (c) 2002 - 2008 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing the bookmark dialog of the helpviewer.
"""

import os

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from Ui_BookmarkDialog import Ui_BookmarkDialog

class BookmarkDialog(QDialog, Ui_BookmarkDialog):
    """
    Class implementing the bookmark dialog of the helpviewer.
    
    This dialog is used to edit and delete individual bookmarks.
    They can be rearranged and their contents can be edited.
    """
    def __init__(self,parent,name=QString(),fl = Qt.WindowFlags(Qt.Widget)):
        """
        Constructor
        
        @param parent the parent widget of this dialog (QWidget)
                This is usually the helpviewer main window.
        @param name the name of this dialog (string or QString)
        @param fl window flags for this dialog
        """
        QDialog.__init__(self,parent,fl)
        self.setupUi(self)
        self.setObjectName(name)
        
        self.parent = parent
        self.editMode = False
        
    def __resizeColumns(self):
        """
        Private method to resize the list columns.
        """
        self.bookmarkList.doItemsLayout()
        self.bookmarkList.header().resizeSections(QHeaderView.ResizeToContents)
        self.bookmarkList.header().setStretchLastSection(True)
        
    def __populateBookmarkList(self):
        """
        Private function to set up the contents of the listview.
        """
        txtColor = QApplication.palette().color(QPalette.Text)
        self.bookmarkList.clear()
        
        mBookmarks = self.parent.__class__.mBookmarks
        for i in range(0, len(mBookmarks["Names"])):
            itm = QTreeWidgetItem(self.bookmarkList) 
            itm.setText(0, mBookmarks["Names"][i])
            itm.setText(1, mBookmarks["Files"][i])
            itm.setTextColor(0, txtColor)
            itm.setTextColor(1, txtColor)
        self.__resizeColumns()
        
    @pyqtSignature("")
    def on_upButton_clicked(self):
        """
        Private slot called to move the selected item up in the list.
        """
        itm = self.bookmarkList.currentItem()
        if itm is None:
            # nothing selected
            return
            
        index = self.bookmarkList.indexOfTopLevelItem(itm)
        if index == 0:
            # we're already at the top
            return
            
        itm = self.bookmarkList.takeTopLevelItem(index)
        self.bookmarkList.insertTopLevelItem(index-1, itm)
        self.bookmarkList.setCurrentItem(itm)
        if index == 1:
            self.upButton.setEnabled(False)
            self.downButton.setEnabled(True)
        else:
            self.upButton.setEnabled(True)
            self.downButton.setEnabled(True)
        self.__resizeColumns()
        
    @pyqtSignature("")
    def on_downButton_clicked(self):
        """
        Private slot called to move the selected item down in the list.
        """
        itm = self.bookmarkList.currentItem()
        if itm is None:
            # nothing selected
            return
            
        index = self.bookmarkList.indexOfTopLevelItem(itm)
        rows = self.bookmarkList.topLevelItemCount()
        if index ==  rows - 1:
            # we're already at the end
            return
        itm = self.bookmarkList.takeTopLevelItem(index)
        self.bookmarkList.insertTopLevelItem(index+1, itm)
        self.bookmarkList.setCurrentItem(itm)
        if index == rows - 2:
            self.upButton.setEnabled(True)
            self.downButton.setEnabled(False)
        else:
            self.upButton.setEnabled(True)
            self.downButton.setEnabled(True)
        self.__resizeColumns()
        
    def on_bookmarkList_currentItemChanged(self, current, previous):
        """
        Private slot called, when the current item changes.
        
        @param current reference to the new current item (QTreeWidgetItem)
        @param previous reference to the previous current item (QTreeWidgetItem) (ignored)
        """
        if current is None or self.editMode:
            # nothing selected or edit mode enabled
            return
            
        index = self.bookmarkList.indexOfTopLevelItem(current)
        maxIndex = self.bookmarkList.topLevelItemCount() - 1
        self.upButton.setEnabled(index != 0)
        self.downButton.setEnabled(index != maxIndex)
        self.deleteButton.setEnabled(True)
        
    @pyqtSignature("")
    def on_deleteButton_clicked(self):
        """
        Private slot called to delete a listview item.
        """
        itm = self.bookmarkList.currentItem()
        if itm is None:
            # nothing selected
            return
            
        index = self.bookmarkList.indexOfTopLevelItem(itm)
        itm = self.bookmarkList.takeTopLevelItem(index)
        del itm
        self.__resizeColumns()
        
    @pyqtSignature("bool")
    def on_editButton_toggled(self, checked):
        """
        Private slot to switch the edit mode.
        
        @param checked flag indicating the button state (boolean)
        """
        self.editMode = checked
        itm = self.bookmarkList.currentItem()
        
        # step 1: set the button states
        if checked:
            self.upButton.setEnabled(False)
            self.downButton.setEnabled(False)
            self.deleteButton.setEnabled(False)
        else:
            self.upButton.setEnabled(itm is not None)
            self.downButton.setEnabled(itm is not None)
            self.deleteButton.setEnabled(itm is not None)
            if itm is not None:
                self.on_bookmarkList_currentItemChanged(itm, None)
        
        # step 2: set all items to editable
        for i in range(0, self.bookmarkList.topLevelItemCount()):
            titm = self.bookmarkList.topLevelItem(i)
            if checked:
                titm.setFlags(titm.flags() | Qt.ItemFlags(Qt.ItemIsEditable))
            else:
                titm.setFlags(titm.flags() & ~Qt.ItemFlags(Qt.ItemIsEditable))
        
    def accept(self):
        """
        Private slot called if the Ok button is pressed.
        
        It updates the bookmarks list and writes it to
        the bookmarks file.
        """
        self.parent.__class__.mBookmarks["Names"] = QStringList()
        self.parent.__class__.mBookmarks["Files"] = QStringList()
        for i in range(0, self.bookmarkList.topLevelItemCount()):
            itm = self.bookmarkList.topLevelItem(i)
            self.parent.__class__.mBookmarks["Names"].append(itm.text(0))
            self.parent.__class__.mBookmarks["Files"].append(itm.text(1))
        self.parent.writeBookmarks()
        QDialog.accept(self)
        
    def show(self):
        """
        Public slot called to display this dialog.
        """
        self.__populateBookmarkList()
        QDialog.show(self)
        self.__resizeColumns()
