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

# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# 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.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QWidget, QMessageBox)
import MySQLdb as mdb
from contextlib import closing

from create_project import Ui_CreateProjectInfoWindow
from edit_info import Ui_EditInfoWindow
from long_desc import Ui_LongDescWindow
from project import Ui_ProjectWindow

db = mdb.connect('127.0.0.1', 'root', '', 'interSys')

projects_dict = {}
versions_dict = {}


class Ui_MainWindow(QWidget):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        # MainWindow.resize(1162, 861)
        MainWindow.setFixedSize(1162, 861)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.createBtn = QtWidgets.QPushButton(self.centralwidget)
        self.createBtn.setGeometry(QtCore.QRect(850, 10, 191, 41))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.createBtn.setFont(font)
        self.createBtn.setObjectName("createBtn")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(40, 10, 591, 51))
        self.label.setObjectName("label")
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(0, 70, 1161, 16))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(240, 80, 121, 51))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(760, 80, 151, 51))
        self.label_3.setObjectName("label_3")
        self.editProjInfoBtn = QtWidgets.QPushButton(self.centralwidget)
        self.editProjInfoBtn.setGeometry(QtCore.QRect(170, 350, 89, 25))
        self.editProjInfoBtn.setFont(font)
        self.editProjInfoBtn.setObjectName("editProjInfoBtn")
        self.deleteProjBtn = QtWidgets.QPushButton(self.centralwidget)
        self.deleteProjBtn.setGeometry(QtCore.QRect(330, 350, 89, 25))
        self.deleteProjBtn.setFont(font)
        self.deleteProjBtn.setObjectName("deleteProjBtn")
        self.editVerInfoBtn = QtWidgets.QPushButton(self.centralwidget)
        self.editVerInfoBtn.setGeometry(QtCore.QRect(690, 350, 89, 25))
        self.editVerInfoBtn.setFont(font)
        self.editVerInfoBtn.setObjectName("editVerInfoBtn")
        self.deleteVerBtn = QtWidgets.QPushButton(self.centralwidget)
        self.deleteVerBtn.setGeometry(QtCore.QRect(850, 350, 89, 25))
        self.deleteVerBtn.setFont(font)
        self.deleteVerBtn.setObjectName("deleteVerBtn")
        self.listWidget = QtWidgets.QListWidget(self.centralwidget)
        self.listWidget.setGeometry(QtCore.QRect(80, 130, 461, 275))
        self.listWidget.setObjectName("listWidget")
        # item = QtWidgets.QListWidgetItem()
        # font = QtGui.QFont()
        # font.setPointSize(14)
        # item.setFont(font)
        # self.listWidget.addItem(item)
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(590, 130, 471, 275))
        self.tableWidget.setFont(font)
        self.tableWidget.setSelectionBehavior(QtWidgets.QTableView.SelectRows)
        self.tableWidget.setLineWidth(1)
        self.tableWidget.setTextElideMode(QtCore.Qt.ElideRight)
        self.tableWidget.setShowGrid(True)
        self.tableWidget.setWordWrap(True)
        self.tableWidget.setCornerButtonEnabled(True)
        self.tableWidget.setObjectName("tableWidget")
        self.tableWidget.setColumnCount(2)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        item.setFont(font)
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        item.setFont(font)
        self.tableWidget.setHorizontalHeaderItem(1, item)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(234)
        self.tableWidget.verticalHeader().setCascadingSectionResizes(False)
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(150, 420, 301, 51))
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(660, 420, 311, 51))
        self.label_5.setObjectName("label_5")
        self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
        self.textBrowser.setGeometry(QtCore.QRect(80, 480, 461, 205))
        self.textBrowser.setFont(font)
        self.textBrowser_2 = QtWidgets.QTextBrowser(self.centralwidget)
        self.textBrowser_2.setGeometry(QtCore.QRect(590, 480, 471, 205))
        self.textBrowser_2.setObjectName("textBrowser_2")
        self.textBrowser_2.setFont(font)
        self.viewProjDescBtn = QtWidgets.QPushButton(self.centralwidget)
        self.viewProjDescBtn.setGeometry(QtCore.QRect(180, 710, 241, 25))
        self.viewProjDescBtn.setFont(font)
        self.viewProjDescBtn.setObjectName("viewProjDescBtn")
        self.viewVerDescBtn = QtWidgets.QPushButton(self.centralwidget)
        self.viewVerDescBtn.setGeometry(QtCore.QRect(700, 710, 241, 25))
        self.viewVerDescBtn.setFont(font)
        self.viewVerDescBtn.setObjectName("viewVerDescBtn")
        self.openBtn = QtWidgets.QPushButton(self.centralwidget)
        self.openBtn.setGeometry(QtCore.QRect(988, 744, 101, 41))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.openBtn.setFont(font)
        self.openBtn.setObjectName("openBtn")
        self.tableWidget.raise_()
        self.listWidget.raise_()
        self.createBtn.raise_()
        self.label.raise_()
        self.line.raise_()
        self.label_2.raise_()
        self.label_3.raise_()
        self.editProjInfoBtn.raise_()
        self.deleteProjBtn.raise_()
        self.editVerInfoBtn.raise_()
        self.deleteVerBtn.raise_()
        self.label_4.raise_()
        self.label_5.raise_()
        self.textBrowser.raise_()
        self.textBrowser_2.raise_()
        self.viewProjDescBtn.raise_()
        self.viewVerDescBtn.raise_()
        self.openBtn.raise_()
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1162, 22))
        self.menubar.setObjectName("menubar")
        self.menuInteractive_System_Modelling = QtWidgets.QMenu(self.menubar)
        self.menuInteractive_System_Modelling.setObjectName("menuInteractive_System_Modelling")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuInteractive_System_Modelling.menuAction())

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

        self.version_id = QtWidgets.QLabel(self.centralwidget)
        self.version_id.setGeometry(QtCore.QRect(0, 0, 0, 0))
        self.version_id.setObjectName("version_id")

        self.createBtn.clicked.connect(self.new_project)
        self.editProjInfoBtn.clicked.connect(self.edit_project)
        self.editVerInfoBtn.clicked.connect(self.edit_version)
        self.viewProjDescBtn.clicked.connect(self.project_desc)
        self.viewVerDescBtn.clicked.connect(self.version_desc)
        self.deleteProjBtn.clicked.connect(self.delete_project)
        self.deleteVerBtn.clicked.connect(self.delete_version)
        self.openBtn.clicked.connect(self.open_project)
        self.listWidget.itemClicked.connect(self.show_project_short_descr)
        self.listWidget.itemClicked.connect(self.show_versions)
        self.tableWidget.itemClicked.connect(self.show_version_short_descr)
        self.get_projects()

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.updateWindow)
        self.timer.start(10000)

    def updateWindow(self):
        self.get_projects()

    def show_versions(self):
        listItems = self.listWidget.selectedItems()
        if not listItems: return
        for item in listItems:
            self.tableWidget.setRowCount(0)
            db = mdb.connect('127.0.0.1', 'root', '', 'interSys')
            with closing(db.cursor()) as cur:
                cur.execute(
                    "SELECT T2.id, T2.name, T2.project_name, T2.numb, T2.short_descr, T2.long_descr FROM projects T1 INNER JOIN versions T2 ON T1.name = T2.project_name WHERE T1.name = '%s' ORDER BY T2.numb" % (
                        ''.join(item.text())))
                versions = cur.fetchall()

                i = 0
                for y in versions:
                    self.tableWidget.setRowCount(i + 1)
                    self.tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(str(y[1])))
                    self.tableWidget.setItem(i, 1, QtWidgets.QTableWidgetItem(str(y[3])))
                    versions_dict[y[1]] = [y[2], y[3], y[4], y[5], y[0]]
                    i += 1
            db.close()

    def show_project_short_descr(self):
        listItems = self.listWidget.selectedItems()
        if not listItems: return
        for item in listItems:
            self.textBrowser.clear()
            self.textBrowser.append(projects_dict[item.text()][0])

    def show_version_short_descr(self):
        curr_row = self.tableWidget.currentRow()
        curr_col = 0
        self.textBrowser_2.clear()
        item = self.tableWidget.item(curr_row, curr_col)
        self.textBrowser_2.append(versions_dict[item.text()][2])

    def get_projects(self):
        self.listWidget.clear()
        # _translate = QtCore.QCoreApplication.translate
        db = mdb.connect('127.0.0.1', 'root', '', 'interSys')
        with closing(db.cursor()) as cur:
            cur.execute("SELECT * FROM projects")
            projects = cur.fetchall()

            for x in projects:
                item = QtWidgets.QListWidgetItem()
                item.setText(x[1])
                font = QtGui.QFont()
                font.setPointSize(14)
                item.setFont(font)
                self.listWidget.addItem(item)
                projects_dict[x[1]] = [x[2], x[3]]
        db.close()

    def delete_project(self):
        listItems = self.listWidget.selectedItems()
        if not listItems: return
        reply = QMessageBox.question(self, "Delete project",
                                     "Are you sure you want to delete this project and its versions?",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            for item in listItems:
                self.listWidget.takeItem(self.listWidget.row(item))
                db = mdb.connect('127.0.0.1', 'root', '', 'interSys')
                with closing(db.cursor()) as cur:
                    cur.execute("DELETE FROM versions WHERE project_name = '%s'" % (''.join(item.text())))
                    cur.execute("DELETE FROM projects WHERE name = '%s'" % (''.join(item.text())))
                    db.commit()
                    self.tableWidget.clear()
                    self.textBrowser.clear()
                    self.textBrowser_2.clear()
                db.close()
        else:
            return

    def delete_version(self):
        curr_row = self.tableWidget.currentRow()
        curr_col = 0
        project_name = self.listWidget.currentItem()

        if curr_row == -1 and curr_col == -1:
            return
        ver_name = self.tableWidget.item(curr_row, curr_col)
        reply = QMessageBox.question(self, "Delete version", "Are you sure you want to delete this version?",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:

            self.textBrowser_2.clear()
            db = mdb.connect('127.0.0.1', 'root', '', 'interSys')
            with closing(db.cursor()) as cur:
                cur.execute("DELETE FROM versions WHERE name = '%s' AND project_name = '%s'" % (
                ''.join(ver_name.text()), ''.join(project_name.text())))
                db.commit()
                self.tableWidget.removeRow(curr_row)
                self.textBrowser_2.clear()
            db.close()
        else:
            return

    def new_project(self):
        self.CreateProjectInfoWindow = QtWidgets.QMainWindow()
        self.ui = Ui_CreateProjectInfoWindow()
        self.ui.setupUi(self.CreateProjectInfoWindow)
        self.CreateProjectInfoWindow.show()

    def edit_project(self):
        listItems = self.listWidget.selectedItems()
        if not listItems: return
        for item in listItems:
            project = [item.text(), projects_dict[item.text()][0], projects_dict[item.text()][1]]
            self.edit(project, '', project[0])

    def edit_version(self):
        listItems = self.listWidget.selectedItems()
        if not listItems: return
        for x in listItems:
            curr_row = self.tableWidget.currentRow()
            curr_col = 0
            item = self.tableWidget.item(curr_row, curr_col)
            version = [item.text(), versions_dict[item.text()][2], versions_dict[item.text()][3]]
            self.edit(version, "Version " + str(versions_dict[item.text()][1]), x.text())

    def edit(self, item, ver_num, proj_name):
        self.EditInfoWindow = QtWidgets.QMainWindow()
        self.ui = Ui_EditInfoWindow()
        self.ui.setupUi(self.EditInfoWindow)
        self.ui.label_3.setText(proj_name)
        self.ui.label_7.setText(ver_num)
        self.ui.lineEdit.setText(item[0])
        self.ui.origin_name = item[0]
        self.ui.textEdit.setText(item[1])
        self.ui.textEdit_2.setText(item[2])
        self.EditInfoWindow.show()

    def project_desc(self):
        list_items = self.listWidget.selectedItems()
        if not list_items: return
        for item in list_items:
            text = projects_dict[item.text()][1]
            self.show_long_desc(text)

    def version_desc(self):
        curr_row = self.tableWidget.currentRow()
        curr_col = self.tableWidget.currentColumn()
        item = self.tableWidget.item(curr_row, curr_col)
        text = versions_dict[item.text()][3]
        self.show_long_desc(text)

    def show_long_desc(self, text):
        self.LongDescWindow = QtWidgets.QMainWindow()
        self.ui = Ui_LongDescWindow()
        self.ui.setupUi(self.LongDescWindow)
        self.ui.textBrowser.clear()
        self.ui.textBrowser.append(text)
        self.LongDescWindow.show()

    def open_project(self):
        listItems = self.listWidget.selectedItems()
        curr_row = self.tableWidget.currentRow()
        curr_col = self.tableWidget.currentColumn()
        ver_name = self.tableWidget.item(curr_row, curr_col)
        if not listItems: return
        if curr_row == -1 and curr_col == -1:
            return
        for item in listItems:
            cur_name = item.text()

        cur_vers = str(versions_dict[ver_name.text()][1]) + ': ' + ver_name.text()
        self.ProjectWindow = QtWidgets.QMainWindow()
        self.ui = Ui_ProjectWindow()
        self.ui.setupUi(self.ProjectWindow)
        self.ui.label.setText('Project: ' + cur_name)
        self.ui.label_2.setText('Version ' + cur_vers)
        self.ui.version_name.setText(ver_name.text())
        self.ui.project_name.setText(cur_name)
        self.ui.version_number.setText(str(versions_dict[ver_name.text()][1]))
        self.ui.vers_short_descr.setText(str(versions_dict[ver_name.text()][2]))
        self.ui.vers_long_descr.setText(str(versions_dict[ver_name.text()][3]))
        self.ui.version_id.setText(str(versions_dict[ver_name.text()][4]))
        self.ProjectWindow.show()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.createBtn.setText(_translate("MainWindow", "Create a Project"))
        self.label.setText(_translate("MainWindow",
                                      "<html><head/><body><p><span style=\" font-size:28pt;\">Interactive System Modelling</span></p></body></html>"))
        self.label_2.setText(_translate("MainWindow",
                                        "<html><head/><body><p><span style=\" font-size:20pt;\">Projects</span></p></body></html>"))
        self.label_3.setText(_translate("MainWindow",
                                        "<html><head/><body><p><span style=\" font-size:20pt;\">Versions</span></p></body></html>"))
        self.editProjInfoBtn.setText(_translate("MainWindow", "Edit Info"))
        self.deleteProjBtn.setText(_translate("MainWindow", "Delete"))
        self.editVerInfoBtn.setText(_translate("MainWindow", "Edit Info"))
        self.deleteVerBtn.setText(_translate("MainWindow", "Delete"))
        __sortingEnabled = self.listWidget.isSortingEnabled()
        self.listWidget.setSortingEnabled(False)
        self.listWidget.setSortingEnabled(__sortingEnabled)
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "Name"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "Version #"))
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        self.tableWidget.setSortingEnabled(__sortingEnabled)
        self.label_4.setText(_translate("MainWindow",
                                        "<html><head/><body><p><span style=\" font-size:20pt;\">Project Description</span></p></body></html>"))
        self.label_5.setText(_translate("MainWindow",
                                        "<html><head/><body><p><span style=\" font-size:20pt;\">Version Description</span></p></body></html>"))
        self.viewProjDescBtn.setText(_translate("MainWindow", "View Long Description"))
        self.viewVerDescBtn.setText(_translate("MainWindow", "View Long Description"))
        self.openBtn.setText(_translate("MainWindow", "Open"))


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()

    sys.exit(app.exec_())
