from PyQt4 import QtCore, QtGui

class TreeItem(object):
    def __init__(self, data, parent=None):
        self.parentItem = parent
        self.itemData = data
        self.childItems = []
        self.radiogroup = []
        self.checktype = None # None, "checkbox", or "radiobutton"
        
        # Lame implementation for now.
        if data[0][0] == "x":
            self.checktype = "checkbox"
        elif data[0][0] == "o":
            self.checktype = "radiobutton"
            if parent:
                parent.radiogroup.append(self)
                
        self.checked = False
        if self.checktype:
            # Prevent bad configs causing multiple radiobuttons to be checked.
            # Still a lame implementation.
            self.setChecked(data[1][0] == "x") 
        
    def setChecked(self, state):
        if self.checked == state:
            # Nothing to do here.
            return
        
        if self.checktype == "radiobutton" and state == True:
            # Uncheck any other items in the parent's radiogroup
            self.parentItem.clearRadioSelections()
            
        self.checked = state

    def clearRadioSelections(self):
        for item in self.radiogroup:
            # 'Exclusive' implementation for radiobuttons
            item.setChecked(False)
            
    def appendChild(self, item):
        self.childItems.append(item)

    def child(self, row):
        return self.childItems[row]

    def childCount(self):
        return len(self.childItems)

    def columnCount(self):
        return len(self.itemData)

    def data(self, column):
        try:
            return self.itemData[column]
        except IndexError:
            return None

    def parent(self):
        return self.parentItem

    def row(self):
        if self.parentItem:
            return self.parentItem.childItems.index(self)

        return 0

class TreeModel(QtCore.QAbstractItemModel):
    def __init__(self, data, parent=None):
        super(TreeModel, self).__init__(parent)

        self.rootItem = TreeItem(("Title", "Summary"))
        self.setupModelData(data.split('\n'), self.rootItem)

    def columnCount(self, parent):
        if parent.isValid():
            return parent.internalPointer().columnCount()
        else:
            return self.rootItem.columnCount()
            
    def getItemByIndex(self, index):
        if not index.isValid():
            return None
            
        item = index.internalPointer()
        return item

    def data(self, index, role):
        if not index.isValid():
            return None

        if role != QtCore.Qt.DisplayRole and role != QtCore.Qt.CheckStateRole:
            return None
            
        item = self.getItemByIndex(index)

        if role == QtCore.Qt.DisplayRole:
            return item.data(index.column())
        elif role == QtCore.Qt.CheckStateRole and item.checktype and index.column() == 0:
            return QtCore.Qt.Checked if item.checked else QtCore.Qt.Unchecked
            
    def setData(self, index, value, role):
        print index.internalId()
        status = False
        item = self.getItemByIndex(index)
        
        if role == QtCore.Qt.CheckStateRole:
            if index.column() == 0:
                if not item.checked:
                    # setChecked(bool) deselects any radiobutton items in the same group
                    # Need to find a way to refresh programmatically toggled items
                    item.setChecked(True)
                else:
                    item.setChecked(False)
                status = True
                self.emit(QtCore.SIGNAL('dataChanged(QModelIndex,QModelIndex)'), index, index)
        return status

    def flags(self, index):
        if not index.isValid():
            return QtCore.Qt.NoItemFlags
        
        flags = QtCore.Qt.ItemIsEnabled
        item = self.getItemByIndex(index)
        
        if item.checktype != None:
            flags |= QtCore.Qt.ItemIsUserCheckable
        
        return flags

    def headerData(self, section, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return self.rootItem.data(section)

        return None

    def index(self, row, column, parent):
        if not self.hasIndex(row, column, parent):
            return QtCore.QModelIndex()

        if not parent.isValid():
            parentItem = self.rootItem
        else:
            parentItem = parent.internalPointer()

        childItem = parentItem.child(row)
        if childItem:
            retn = self.createIndex(row, column, childItem)
            return retn
        else:
            return QtCore.QModelIndex()

    def parent(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()

        childItem = self.getItemByIndex(index)
        parentItem = childItem.parent()

        if parentItem == self.rootItem:
            return QtCore.QModelIndex()

        return self.createIndex(parentItem.row(), 0, parentItem)

    def rowCount(self, parent):
        if parent.column() > 0:
            return 0

        if not parent.isValid():
            parentItem = self.rootItem
        else:
            parentItem = parent.internalPointer()

        return parentItem.childCount()

    def setupModelData(self, lines, parent):
        # To be replaced with a ConfigObj implementation
        parents = [parent]
        indentations = [0]

        number = 0

        while number < len(lines):
            position = 0
            while position < len(lines[number]):
                if lines[number][position] != ' ':
                    break
                position += 1

            lineData = lines[number][position:].trimmed()

            if lineData:
                # Read the column data from the rest of the line.
                columnData = [s for s in lineData.split('\t') if s]

                if position > indentations[-1]:
                    # The last child of the current parent is now the new
                    # parent unless the current parent has no children.

                    if parents[-1].childCount() > 0:
                        parents.append(parents[-1].child(parents[-1].childCount() - 1))
                        indentations.append(position)

                else:
                    while position < indentations[-1] and len(parents) > 0:
                        parents.pop()
                        indentations.pop()

                # Append a new item to the current parent's list of children.
                item = TreeItem(columnData, parents[-1])
                parents[-1].appendChild(item)

            number += 1

class MyDelegate(QtGui.QItemDelegate):
    def paint(self, painter, option, index):
        # Save the current item for later, to allow us to differentiate between
        # what kind of checkbox to draw. Purely aesthetic.
        self.currentItem = index.internalPointer()
        super(MyDelegate, self).paint(painter, option, index)

    def drawCheck( self, painter, option, rect, state ):
        if not rect.isValid(): 
            return
        option.rect = rect
        option.state &= ~QtGui.QStyle.State_HasFocus
        option.state |= {
            QtCore.Qt.Unchecked: QtGui.QStyle.State_Off,
            QtCore.Qt.PartiallyChecked: QtGui.QStyle.State_NoChange,
            QtCore.Qt.Checked: QtGui.QStyle.State_On
        }[ state ]
        style = self.view.style() if self.view else QtGuiQApplication.style()
        
        if self.currentItem.checktype == "radiobutton":
            style.drawPrimitive( QtGui.QStyle.PE_IndicatorRadioButton, option, painter, self.view )
        else:
            style.drawPrimitive( QtGui.QStyle.PE_IndicatorViewItemCheck, option, painter, self.view )

if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)

    f = QtCore.QFile('default.txt')
    f.open(QtCore.QIODevice.ReadOnly)
    model = TreeModel(f.readAll())
    f.close()

    view = QtGui.QTreeView()
    view.setModel(model)
    delegate = MyDelegate()
    delegate.view = view
    view.setItemDelegate(delegate)
    view.setWindowTitle("Simple Tree Model")
    view.show()
    sys.exit(app.exec_())
