from ...Qt import QtWidgets, QtCore, QtGui
from ...lib.delegates import PropertyDelegate


class PropWidget(QtWidgets.QWidget):
    propertyChanged = QtCore.pyqtSignal(str, str, object)

    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.setContentsMargins(2, 2, 2, 2)
        self.tab = QtWidgets.QTabWidget(self)
        self.layout.addWidget(self.tab)
        self.pages = []

        self.tab.currentChanged.connect(self.tab_change)

        self._tab_idx = 0

    def populate(self, props: dict):
        self.pages = []
        self.tab.blockSignals(True)
        while self.tab.count():
            self.tab.removeTab(0)

        for k, v in props.items():
            table = PropTable(self)
            table.populate(v)
            table.itemChanged.connect(self.property_change)
            self.tab.addTab(table, k)
            self.pages.append(table)
        self.tab.blockSignals(False)

        self.tab.setCurrentIndex(self._tab_idx)

    @QtCore.pyqtSlot(QtWidgets.QTableWidgetItem)
    def property_change(self, item: QtWidgets.QTableWidgetItem):
        tab_idx = self.tab.currentIndex()
        table = self.pages[tab_idx]
        idx = table.indexFromItem(item)
        self.propertyChanged.emit(self.tab.tabText(tab_idx),
                                  table.item(idx.row(), idx.column()-1).text(),
                                  item.data(QtCore.Qt.DisplayRole))

    @QtCore.pyqtSlot(int)
    def tab_change(self, idx: int):
        self._tab_idx = idx


class PropTable(QtWidgets.QTableWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.setColumnCount(2)
        self.setItemDelegateForColumn(1, PropertyDelegate())
        self.horizontalHeader().setStretchLastSection(True)
        self.verticalHeader().setVisible(False)
        self.horizontalHeader().setVisible(False)
        self.setFrameShape(QtWidgets.QFrame.NoFrame)
        self.setFrameShadow(QtWidgets.QFrame.Plain)

    def populate(self, prop: dict):
        self.clear()
        self.setRowCount(0)
        self.blockSignals(True)
        for k, v in prop.items():
            value_item = QtWidgets.QTableWidgetItem('')
            value_item.setData(QtCore.Qt.DisplayRole, v)

            key_item = QtWidgets.QTableWidgetItem(k)
            key_item.setFlags(QtCore.Qt.NoItemFlags)
            key_item.setForeground(QtGui.QBrush(QtGui.QColor(0, 0, 0)))

            self.setRowCount(self.rowCount()+1)
            self.setItem(self.rowCount()-1, 0, key_item)
            self.setItem(self.rowCount()-1, 1, value_item)
        self.blockSignals(False)
