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

# Form implementation generated from reading ui file 'create_project.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)

from result_semantic_memory import Ui_ResultsSemanticMemoryWindow
from functions_with_db import get_sem_mem, get_exp
from translation_to_Maude import read_Maude_file, write_stm_capacity_to_Maude, write_cognitive_load_to_Maude, write_decay_time_to_Maude, \
    write_rewrite_steps_to_Maude, write_sem_mem_to_Maude, write_exp_to_Maude, write_stm_to_Maude, reset_Maude_file, write_to_Maude_file

import MySQLdb as mdb
from contextlib import closing

import subprocess

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

class Ui_RunLearnWindow(object):
    def setupUi(self, RunLearnWindow):
        RunLearnWindow.setObjectName("RunLearnWindow")
        RunLearnWindow.setFixedSize(480, 800)
        self.centralwidget = QtWidgets.QWidget(RunLearnWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(40, 10, 591, 51))
        self.label.setObjectName("label")
        font = QtGui.QFont()
        font.setPointSize(14)
        self.project_name = QtWidgets.QLabel(self.centralwidget)
        self.project_name.setGeometry(QtCore.QRect(40, 80, 351, 51))
        self.project_name.setObjectName("project_name")
        self.project_name.setFont(font)
        self.version_name = QtWidgets.QLabel(self.centralwidget)
        self.version_name.setGeometry(QtCore.QRect(40, 120, 351, 51))
        self.version_name.setObjectName("version_name")
        self.version_name.setFont(font)
        self.version_id = QtWidgets.QLabel(self.centralwidget)
        self.version_id.setGeometry(QtCore.QRect(0, 0, 0, 0))
        self.version_id.setObjectName("version_id")

        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(0, 80, 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(40, 170, 351, 51))
        self.label_2.setObjectName("label_2")
        self.label_2.setFont(font)
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(40, 270, 351, 51))
        self.label_4.setObjectName("label_4")
        self.label_4.setFont(font)
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(40, 370, 351, 51))
        self.label_5.setObjectName("label_5")
        self.label_5.setFont(font)
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(40, 470, 351, 51))
        self.label_6.setObjectName("label_6")
        self.label_6.setFont(font)
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(40, 570, 351, 51))
        self.label_7.setObjectName("label_7")
        self.label_7.setFont(font)
        self.stm_capacity = QtWidgets.QLineEdit(self.centralwidget)
        self.stm_capacity.setGeometry(QtCore.QRect(40, 220, 400, 41))
        self.stm_capacity.setObjectName("stm_capacity")
        self.stm_capacity.setFont(font)
        self.cogn_load = QtWidgets.QLineEdit(self.centralwidget)
        self.cogn_load.setGeometry(QtCore.QRect(40, 320, 400, 41))
        self.cogn_load.setObjectName("stm_capacity")
        self.cogn_load.setFont(font)
        self.decay_time = QtWidgets.QLineEdit(self.centralwidget)
        self.decay_time.setGeometry(QtCore.QRect(40, 420, 400, 41))
        self.decay_time.setObjectName("decay_time")
        self.decay_time.setFont(font)
        self.in_time = QtWidgets.QLineEdit(self.centralwidget)
        self.in_time.setGeometry(QtCore.QRect(40, 520, 400, 41))
        self.in_time.setObjectName("in_time")
        self.in_time.setFont(font)
        self.rewrite_steps = QtWidgets.QLineEdit(self.centralwidget)
        self.rewrite_steps.setGeometry(QtCore.QRect(40, 620, 400, 41))
        self.rewrite_steps.setObjectName("rewrite_steps")
        self.rewrite_steps.setFont(font)
        self.runBtn = QtWidgets.QPushButton(self.centralwidget)
        self.runBtn.setGeometry(QtCore.QRect(195, 700, 90, 25))
        # self.runBtn.clicked.connect(self.create_project)
        self.runBtn.clicked.connect(RunLearnWindow.close)
        self.runBtn.setFont(font)
        self.runBtn.setObjectName("runBtn")
        RunLearnWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(RunLearnWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 553, 22))
        self.menubar.setObjectName("menubar")
        self.menuInteractive_System_Modelling = QtWidgets.QMenu(self.menubar)
        self.menuInteractive_System_Modelling.setObjectName("menuInteractive_System_Modelling")
        RunLearnWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(RunLearnWindow)
        self.statusbar.setObjectName("statusbar")
        RunLearnWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuInteractive_System_Modelling.menuAction())

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

        self.runBtn.clicked.connect(self.run)

    def create_result_window(self):
        self.ResultsSemanticMemoryWindow = QtWidgets.QMainWindow()
        self.ui = Ui_ResultsSemanticMemoryWindow()
        self.ui.setupUi(self.ResultsSemanticMemoryWindow)
        self.ui.label_2.setText(self.label.text())
        self.ui.label_3.setText(self.label_2.text())
        self.ui.version_id.setText(self.version_id.text())

    def get_old_sem_mem_from_db(self, version_id):
        self.ui.oldTableWidget.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.ui.oldTableWidget.setRowCount(i + 1)
                self.ui.oldTableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(str(y[2])))
                self.ui.oldTableWidget.setItem(i, 1, QtWidgets.QTableWidgetItem(str(y[3])))
                self.ui.oldTableWidget.setItem(i, 2, QtWidgets.QTableWidgetItem(str(y[4])))
                i += 1
            cur.execute("DELETE FROM sem_mem WHERE version_id = '%i'" % (version_id))
            db.commit()
        db.close()

    def save_new_sem_mem(self, version_id):
        sem = {}
        sem_str = "->|"
        f = open("Maude-2/results.txt", "r")
        i = 0
        j = 0
        for line in f:
            i += 1
            if sem_str in line:
                new_line = str(line)
                n = len(new_line)
                start_line = new_line.find('(') + len('(')
                end_line = new_line.find(')')
                cur_line = new_line[start_line:end_line]
                # domain = cur_line.split(' ', 6)[0][1:-1]
                cat = cur_line.split(' ', 6)[2][1:-1]
                time = cur_line.split(' ', 6)[4]
                rest = cur_line.split(' ', 6)[6]
                attr = rest.rsplit(' ', 1)[1][1:-1]
                typ = rest.rsplit(' ', 1)[0]
                val = cat + ' ' + typ + ' ' + attr
                self.ui.newTableWidget.setRowCount(j + 1)
                self.ui.newTableWidget.setItem(j, 0, QtWidgets.QTableWidgetItem(domain))
                self.ui.newTableWidget.setItem(j, 1, QtWidgets.QTableWidgetItem(val))
                self.ui.newTableWidget.setItem(j, 2, QtWidgets.QTableWidgetItem(time))
                j += 1
                db = mdb.connect('127.0.0.1', 'root', '', 'interSys')
                version_id = int(self.version_id.text())
                with closing(db.cursor()) as cur:
                    cur.execute(
                        "INSERT INTO sem_mem(version_id, domain, fact, retr_time, categories, types, attributes)"
                        "VALUES('%i', '%s', '%s', '%i', '%s', '%s', '%s')" % (
                        version_id, domain, val, int(time), cat, typ, attr))
                    db.commit()
        f.close()
        QtWidgets.QMessageBox.about(self.centralwidget,'Connection', 'Data Inserted Successfully')

    def run(self):
        version_id = int(self.version_id.text())
        sem_mem_dict = get_sem_mem(version_id)
        exp_dict = get_exp(version_id)

        list_of_lines = read_Maude_file()
        write_stm_capacity_to_Maude(list_of_lines, self.stm_capacity.text())
        write_cognitive_load_to_Maude(list_of_lines, self.cogn_load.text())
        # write_decay_time_to_Maude(list_of_lines, self.decay_time.text())
        write_rewrite_steps_to_Maude(list_of_lines, self.rewrite_steps.text(), self.in_time.text())

        list_of_lines = read_Maude_file()
        list_of_lines = write_sem_mem_to_Maude(list_of_lines, sem_mem_dict)
        list_of_lines = write_exp_to_Maude(list_of_lines, exp_dict, True)

        list_of_lines = write_stm_to_Maude(list_of_lines, exp_dict, {}, True)
        write_to_Maude_file(list_of_lines)
        subprocess.call("./start_maude.sh")
        self.create_result_window()
        reset_Maude_file()
        self.get_old_sem_mem_from_db(version_id)
        self.save_new_sem_mem(version_id)
        self.ResultsSemanticMemoryWindow.show()

    def retranslateUi(self, RunLearnWindow):
        _translate = QtCore.QCoreApplication.translate
        RunLearnWindow.setWindowTitle(_translate("RunLearnWindow", "MainWindow"))
        self.label.setText(_translate("RunLearnWindow", "<html><head/><body><p><span style=\" font-size:28pt;\">Run Project</span></p></body></html>"))
        self.label_2.setText(_translate("RunLearnWindow", "<html><head/><body><p><span style=\" font-size:14pt;\">STM capacity</span></p></body></html>"))
        self.label_4.setText(_translate("RunLearnWindow", "<html><head/><body><p><span style=\" font-size:14pt;\">Cognitive Load</span></p></body></html>"))
        self.label_5.setText(_translate("RunLearnWindow", "<html><head/><body><p><span style=\" font-size:14pt;\">Decay time</span></p></body></html>"))
        self.label_6.setText(_translate("RunLearnWindow", "<html><head/><body><p><span style=\" font-size:14pt;\">In time</span></p></body></html>"))
        self.label_7.setText(_translate("RunLearnWindow", "<html><head/><body><p><span style=\" font-size:14pt;\">Number of rewrite steps</span></p></body></html>"))
        self.stm_capacity.setText(_translate("RunLearnWindow", "7"))
        self.cogn_load.setText(_translate("RunLearnWindow", "0"))
        self.decay_time.setText(_translate("RunLearnWindow", "3"))
        self.in_time.setText(_translate("RunLearnWindow", "1000"))
        self.rewrite_steps.setText(_translate("RunLearnWindow", "10000"))
        self.runBtn.setText(_translate("RunLearnWindow", "Run"))
        self.menuInteractive_System_Modelling.setTitle(_translate("RunLearnWindow", "1"))

