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

# Form implementation generated from reading ui file 'test_scroll_2.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

# exec python3 -m PyQt5.uic.pyuic test_ui.ui -o test_ui.py -x


from PyQt5 import QtCore, QtGui, QtWidgets
import sys
from seeCode import seeCode


class Ui_MainWindow(object):
    widgetDict = {}
    treeDict = {}

    def __init__(self, codeSeer):
        self.codeSeer = codeSeer
        self.codeArr = codeSeer.code_arr

    def __getitem__(self, key):
        return self.widgetDict[key]

    def __setitem__(self, key, newvalue):
        self.widgetDict[key] = newvalue

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(839, 800)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 813, 438))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.listWidget = QtWidgets.QListWidget(self.scrollAreaWidgetContents)
        self.listWidget.setObjectName("listWidget")

        for line in enumerate(self.codeArr):
            item = QtWidgets.QListWidgetItem()
            self.listWidget.addItem(item)
        
        self.listWidget.setCurrentRow(0)

        self.verticalLayout_2.addWidget(self.listWidget)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.pushButton_3 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
        self.pushButton_3.setObjectName("pushButton_3")
        self.horizontalLayout_2.addWidget(self.pushButton_3)
        self.pushButton_2 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
        self.pushButton_2.setObjectName("pushButton_2")
        self.horizontalLayout_2.addWidget(self.pushButton_2)
        self.pushButton = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
        self.pushButton.setObjectName("pushButton")
        self.horizontalLayout_2.addWidget(self.pushButton)
        self.pushButton_4 = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
        self.pushButton_4.setObjectName("pushButton_4")
        self.horizontalLayout_2.addWidget(self.pushButton_4)
        self.verticalLayout_2.addLayout(self.horizontalLayout_2)
        self.horizontalLayout_3.addLayout(self.verticalLayout_2)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")

            
        self.horizontalLayout_3.addLayout(self.verticalLayout)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.horizontalLayout.addWidget(self.scrollArea)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 839, 24))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton_3.setText(_translate("MainWindow", "Next"))
        self.pushButton_3.clicked.connect(self.next)
        self.pushButton_2.setText(_translate("MainWindow", "Back"))
        self.pushButton_2.clicked.connect(self.back)
        self.pushButton.setText(_translate("MainWindow", "In"))
        self.pushButton_4.setText(_translate("MainWindow", "Out"))
        self.listWidget.setSortingEnabled(False)
        for i, line in enumerate(self.codeArr):
            item = self.listWidget.item(i)
            item.setText(_translate("MainWindow", line))

    def next(self):
        currentSnapshotId = self.codeSeer.current_snapshot["snapshot_id"]
        if currentSnapshotId + 1 < self.codeSeer.snapshot_count:
            updatedSnapshotId = currentSnapshotId + 1
            self.codeSeer.fetch_current_snapshot(updatedSnapshotId)
            self.listWidget.setCurrentRow(self.codeSeer.current_snapshot["line_no"] - 1)
            self.codeSeer.fetch_values(updatedSnapshotId)
            self.removeAllWidgets(self.verticalLayout)
            self.addData(self.codeSeer.locals + self.codeSeer.globals)
            
    
    def back(self):
        currentSnapshotId = self.codeSeer.current_snapshot["snapshot_id"]
        if currentSnapshotId - 1 > 0:
            updatedSnapshotId = currentSnapshotId - 1
            self.codeSeer.fetch_current_snapshot(updatedSnapshotId)
            self.listWidget.setCurrentRow(self.codeSeer.current_snapshot["line_no"] - 1)
            self.codeSeer.fetch_values(updatedSnapshotId)
            self.removeAllWidgets(self.verticalLayout)
            self.addData(self.codeSeer.locals + self.codeSeer.globals)

    
    def selectionChanged(self):
        print("Selected items: ", self.listWidget.selectedItems()[0].text(), " at index", self.listWidget.currentRow())
    
    def addData(self, members):
        _translate = QtCore.QCoreApplication.translate
        for i in range(0, len(members)):
            iStr = str(i)
            key = "treeWidget_" + iStr
            member = members[i]
            widget = QtWidgets.QTreeWidget(self.scrollAreaWidgetContents)
            widget.setObjectName(key)
            self.treeDict[key] = {}
            self.verticalLayout.addWidget(widget)
            widget.headerItem().setText(0, _translate("MainWindow", member["Member_key"]))
            QtWidgets.QTreeWidgetItem(widget)
            __sortingEnabled = widget.isSortingEnabled()
            widget.setSortingEnabled(False)
            hasChildren = member['Member_value_type'] == 7
            if hasChildren:
                self.clickTreeItem(member['Member_value_id'], widget, widget, True)(widget, 0)
            else:
                widget.topLevelItem(0).setText(0, _translate("MainWindow", str(member["Member_value"])))
            widget.setSortingEnabled(__sortingEnabled)

    def removeAllWidgets(self, layout):
        for i in reversed(range(layout.count())): 
            layout.itemAt(i).widget().setParent(None)
    
    def clickTreeItem(self, memberValueId, widget, parent, isTopLevel):
        def _clickTreeItem(it, col):
            if parent != it:
                return
            newMembers = self.codeSeer.getFetchValueSql(memberValueId, self.codeSeer.current_snapshot["snapshot_id"])
            _translate = QtCore.QCoreApplication.translate
            for i in range(0, len(newMembers)):
                member = newMembers[i]
                QtWidgets.QTreeWidgetItem(parent)
                child = parent.topLevelItem(i) if isTopLevel else parent.child(i)
                hasChildren = member['Member_value_type'] == 7
                value =  ": ..." if hasChildren else ": " + str(member["Member_value"])
                child.setText(0, _translate("MainWindow", str(member["Member_key"]) + value))
                if not hasChildren:
                    continue
                widget.itemClicked.connect(self.clickTreeItem(member['Member_value_id'], widget, child, False))
            if not isTopLevel:
                parent.setExpanded(True)
        return _clickTreeItem


class TreeItem(object):
    def __init__(self, widget, path):
        self.widget = widget
        self.path = path

def main():
    if len(sys.argv) < 2:
        print("Please provide a .sqlite file and a version number.")
        return
    filename = sys.argv[1]
    seer = seeCode(filename)
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow(seer)
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
