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

# Form implementation generated from reading ui file 'sem_mem.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 csv
from itertools import zip_longest
import pandas
import io
import MySQLdb as mdb
from contextlib import closing

from add_to_sem_mem import Ui_AddToSemMemWindow
from edit_fact_repr_in_sem_mem import Ui_EditFactReprInSemMemWindow

fact_repr_dict = []

class Ui_SemMemWindow(QWidget):
    def setupUi(self, SemMemWindow):
        SemMemWindow.setObjectName("SemMemWindow")
        SemMemWindow.resize(1159, 861)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(SemMemWindow.sizePolicy().hasHeightForWidth())
        SemMemWindow.setSizePolicy(sizePolicy)
        self.centralwidget = QtWidgets.QWidget(SemMemWindow)
        self.centralwidget.setObjectName("centralwidget")
        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_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(550, 140, 151, 51))
        self.label_4.setObjectName("label_4")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(80, 200, 991, 511))
        font = QtGui.QFont()
        font.setPointSize(14)
        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(3)
        self.tableWidget.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(2, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(14)
        item.setFont(font)
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(14)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        item.setFont(font)
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(14)
        item.setFont(font)
        self.tableWidget.setHorizontalHeaderItem(2, item)
        self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(324)
        self.tableWidget.horizontalHeader().setMinimumSectionSize(71)
        self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
        self.tableWidget.verticalHeader().setCascadingSectionResizes(False)
        self.tableWidget.verticalHeader().setDefaultSectionSize(26)
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(40, 80, 351, 51))
        self.label_2.setObjectName("label_2")
        self.label_2.setFont(font)
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(40, 120, 351, 51))
        self.label_3.setObjectName("label_3")
        self.label_3.setFont(font)
        self.updateBtn = QtWidgets.QPushButton(self.centralwidget)
        self.updateBtn.setGeometry(QtCore.QRect(700, 10, 191, 41))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.updateBtn.setFont(font)
        self.updateBtn.setObjectName("updateBtn")
        self.saveBtn = QtWidgets.QPushButton(self.centralwidget)
        self.saveBtn.setGeometry(QtCore.QRect(900, 10, 191, 41))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.saveBtn.setFont(font)
        self.saveBtn.setObjectName("saveBtn")
        self.addBtn = QtWidgets.QPushButton(self.centralwidget)
        self.addBtn.setGeometry(QtCore.QRect(510, 750, 151, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.addBtn.setFont(font)
        self.addBtn.setObjectName("addBtn")
        self.editBtn = QtWidgets.QPushButton(self.centralwidget)
        self.editBtn.setGeometry(QtCore.QRect(700, 750, 151, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.editBtn.setFont(font)
        self.editBtn.setObjectName("editBtn")
        self.deleteBtn = QtWidgets.QPushButton(self.centralwidget)
        self.deleteBtn.setGeometry(QtCore.QRect(890, 750, 151, 31))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.deleteBtn.setFont(font)
        self.deleteBtn.setObjectName("deleteBtn")
        self.tableWidget.raise_()
        self.label.raise_()
        self.line.raise_()
        self.label_4.raise_()
        self.label_2.raise_()
        self.label_3.raise_()
        self.updateBtn.raise_()
        self.addBtn.raise_()
        self.editBtn.raise_()
        self.deleteBtn.raise_()
        SemMemWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(SemMemWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1159, 22))
        self.menubar.setObjectName("menubar")
        self.menuInteractive_System_Modelling = QtWidgets.QMenu(self.menubar)
        self.menuInteractive_System_Modelling.setObjectName("menuInteractive_System_Modelling")
        SemMemWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(SemMemWindow)
        self.statusbar.setObjectName("statusbar")
        SemMemWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuInteractive_System_Modelling.menuAction())

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

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

        self.updateBtn.clicked.connect(self.getFacts)
        self.addBtn.clicked.connect(self.addFact)
        self.editBtn.clicked.connect(self.editFact)
        self.deleteBtn.clicked.connect(self.deleteFact)
        self.saveBtn.clicked.connect(self.saveFile)


    def editFact(self):
        curr_row = self.tableWidget.currentRow() 
        curr_col = 0
        if curr_row == -1 and curr_col == -1:
            return 
        cur_dom = self.tableWidget.item(curr_row, curr_col).text()
        cur_fact = self.tableWidget.item(curr_row, curr_col+1).text()
        cur_time = self.tableWidget.item(curr_row, curr_col+2).text()

        self.EditFactReprInSemMemWindow = QtWidgets.QMainWindow()
        self.ui = Ui_EditFactReprInSemMemWindow()
        self.ui.setupUi(self.EditFactReprInSemMemWindow)
        self.ui.lineEdit.setText(cur_time)
        self.ui.version_id.setText(self.version_id.text())
        self.ui.label_3.setText(cur_dom + " - " + cur_fact + " - " + cur_time)
        self.ui.origin_dom = cur_dom
        self.ui.origin_fact = cur_fact
        self.EditFactReprInSemMemWindow.show()

    def deleteFact(self):
        version_id = int(self.version_id.text())
        curr_row = self.tableWidget.currentRow() 
        curr_col = 0

        if curr_row == -1 and curr_col == -1:
            return 
        cur_dom = self.tableWidget.item(curr_row, curr_col).text()
        cur_fact = self.tableWidget.item(curr_row, curr_col+1).text()
        reply = QMessageBox.question(self, "Delete fact representation", "Are you sure you want to delete this fact representation?", QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            
            db = mdb.connect('127.0.0.1', 'root', '', 'interSys')
            with closing(db.cursor()) as cur:
                cur.execute("DELETE FROM sem_mem WHERE version_id = '%i' AND domain = '%s' AND fact = '%s'" % (version_id, cur_dom, cur_fact))
                db.commit()
                self.tableWidget.removeRow(curr_row)
            db.close()
        else:
            return

    def getFacts(self):
        version_id = int(self.version_id.text())
        self.tableWidget.setRowCount(0)
        db = mdb.connect('127.0.0.1', 'root', '', 'interSys')
        with closing(db.cursor()) as cur:
            cur.execute("SELECT * FROM sem_mem WHERE version_id = '%i' ORDER BY id" % (version_id))
            fact_repr = cur.fetchall()

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


    def addFact(self):
        self.AddToSemMemWindow = QtWidgets.QMainWindow()
        self.ui = Ui_AddToSemMemWindow()
        self.ui.setupUi(self.AddToSemMemWindow)
        self.ui.version_id.setText(self.version_id.text())
        self.AddToSemMemWindow.show()

    def saveFile(self):

        domains = []
        categories = []
        delays = []
        typed_attr = []
        version_id = int(self.version_id.text())
        db = mdb.connect('127.0.0.1', 'root', '', 'interSys')
        with closing(db.cursor()) as cur:
            cur.execute("SELECT * FROM sem_mem WHERE version_id = '%i' ORDER BY id" % (version_id))
            fact_repr = cur.fetchall()
        
        newFileDir, _ = QtWidgets.QFileDialog.getSaveFileName(self.centralwidget, "Save File", QtCore.QDir.currentPath() , '*.csv')

        with open('{}.csv'.format(newFileDir), 'w') as dbFile:
            wr = csv.writer(dbFile)
            wr.writerow(("Representation", "Domain", "Category", "Delay", "Type", "Attribute"))

            for fact in fact_repr:
                wr.writerow(("Fact", str(fact[2]), str(fact[5]), str(fact[4]), str(fact[6]), str(fact[7])))
            QtWidgets.QMessageBox.about(self.centralwidget,'Connection', 'Data Saved Successfully')

    def retranslateUi(self, SemMemWindow):
        _translate = QtCore.QCoreApplication.translate
        SemMemWindow.setWindowTitle(_translate("SemMemWindow", "MainWindow"))
        self.label.setText(_translate("SemMemWindow", "<html><head/><body><p><span style=\" font-size:28pt;\">Semantic Memory</span></p></body></html>"))
        self.label_4.setText(_translate("SemMemWindow", "<html><head/><body><p><span style=\" font-size:20pt;\">Facts</span></p></body></html>"))
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText(_translate("SemMemWindow", "Domain"))
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText(_translate("SemMemWindow", "Fact"))
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText(_translate("SemMemWindow", "Retrieval Time"))
        __sortingEnabled = self.tableWidget.isSortingEnabled()
        self.tableWidget.setSortingEnabled(False)
        self.tableWidget.setSortingEnabled(__sortingEnabled)
        self.updateBtn.setText(_translate("SemMemWindow", "Update"))
        self.addBtn.setText(_translate("SemMemWindow", "Add"))
        self.editBtn.setText(_translate("SemMemWindow", "Edit"))
        self.deleteBtn.setText(_translate("SemMemWindow", "Delete"))
        self.saveBtn.setText(_translate("DatabaseWindow", "Save"))
        self.menuInteractive_System_Modelling.setTitle(_translate("SemMemWindow", "1"))
