# -*- 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

import MySQLdb as mdb
from contextlib import closing

import subprocess
import re

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

sem_mem_dict = {}
env_dict = {}
exp_dict = {}
stm_dict = {}

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 run(self):
        sem_mem_dict = {}
        env_dict = {}
        exp_dict = {}
        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()

            for y in fact_repr:
                sem_mem_dict[y[3]] = [y[2], y[4], y[5], y[6], y[7]]

            cur.execute("SELECT * FROM environment WHERE version_id = '%i' ORDER BY id" % (version_id))
            perc_repr = cur.fetchall()

            for y in perc_repr:
                env_dict[y[4]] = [y[2], y[3], y[5], y[6], y[7], y[8]]

            cur.execute("SELECT * FROM experiment WHERE version_id = '%i' ORDER BY id" % (version_id))
            perc_repr = cur.fetchall()

            for y in perc_repr:
                exp_dict[y[4]] = [y[2], y[3], y[6], y[7], y[8], y[9], y[5], y[10], y[11]]

        db.close()

        f = open("Maude-2/proj/cifma-2020-2.maude", "r")
        list_of_lines = f.readlines()
        f.close()



        lookup = "op stmCapacity : -> Nat ."
        for i, line in enumerate(list_of_lines, 1):
            if lookup in line:
                break
        addition = "   eq stmCapacity = " + self.stm_capacity.text() + " .\n"
        list_of_lines[i] = addition
        f = open("Maude-2/proj/cifma-2020-2.maude", "w")
        f.writelines(list_of_lines)
        f.close()


        lookup = "eq theHuman = < human : Human | cognitiveLoad"
        for i, line in enumerate(list_of_lines, 1):
            if lookup in line:
                break
        addition = "  eq theHuman = < human : Human | cognitiveLoad : " + self.cogn_load.text() + ",\n"
        list_of_lines[i-1] = addition
        f = open("Maude-2/proj/cifma-2020-2.maude", "w")
        f.writelines(list_of_lines)
        f.close()


        # lookup = "ops DECAY-TIME MAX-RETRIEVAL-TIME : -> TimeInf ."
        # for i, line in enumerate(list_of_lines, 1):
        #     if lookup in line:
        #         break
        # addition = "   eq DECAY-TIME = " + self.decay_time.text() + " .\n"
        # list_of_lines[i] = addition
        # f = open("Maude-2/proj/cifma-2020-2.maude", "w")
        # f.writelines(list_of_lines)
        # f.close()


        lookup = "quit"
        for i, line in enumerate(list_of_lines, 1):
            if lookup in line:
                break
        addition = "(trew [" + self.rewrite_steps.text() + "] in EXAMPLE-DOGS : {init} in time <= " + self.in_time.text() + " .)\n"
        list_of_lines[i-3] = addition
        f = open("Maude-2/proj/cifma-2020-2.maude", "w")
        f.writelines(list_of_lines)
        f.close()


        f = open("Maude-2/proj/cifma-2020-2.maude", "r")
        list_of_lines = f.readlines()
        f.close()
        start_str = "op initSemanticMem : -> SemanticMemory ."
        i=0
        for line in list_of_lines:
            i+=1
            if start_str in line:
                i+=1
                break
        list_of_lines[i] = '  eq initSemanticMem =  \n'
        for y in sem_mem_dict:
            i+=1
            domain = sem_mem_dict[y][0]
            time = str(sem_mem_dict[y][1])
            cat = sem_mem_dict[y][2]
            typ = sem_mem_dict[y][3]
            attr = sem_mem_dict[y][4]
            addition = '("'+domain+'" : "'+cat+'" |- '+time+' ->| ('+typ+' "'+attr+'")) \n'
            list_of_lines.insert(i, addition)
        list_of_lines[i+1] = '.\n'
        f = open("Maude-2/proj/cifma-2020-2.maude", "w")
        f.writelines(list_of_lines)
        f.close()

        start_str = "semanticMem : initSemanticMem > ."
        i=0
        for line in list_of_lines:
            i+=1
            if start_str in line:
                i+=1
                break
        list_of_lines[i] = '  eq init = \n'
        for y in exp_dict:
            i+=1
            domain = exp_dict[y][0]
            item = exp_dict[y][1]
            time = str(exp_dict[y][2])
            cat = exp_dict[y][3]
            typ = exp_dict[y][4]
            attr = exp_dict[y][5]
            time_in = str(exp_dict[y][6])
            rep = str(exp_dict[y][7])
            rep_time_in = str(exp_dict[y][8])
            if item=="fact":
                addition = '(repeat '+rep+' times starting in '+rep_time_in+' : exp(((a "'+cat+'" '+typ+' "'+attr+'") for '+time+') in '+time_in+')) \n' 
                # print (addition)               
                list_of_lines.insert(i, addition)
            if item=="question":
                i-=1
        list_of_lines[i+1] = 'theHuman .\n'
        f = open("Maude-2/proj/cifma-2020-2.maude", "w")
        f.writelines(list_of_lines)
        f.close()

        start_str = "ops init-STM : -> ShortTermMemory ."
        i=0
        for line in list_of_lines:
            i+=1
            if start_str in line:
                i+=1
                break
        list_of_lines[i] = '  eq init-STM = \n'
        for y in exp_dict:
            i+=1
            domain = exp_dict[y][0]
            item = exp_dict[y][1]
            cat = exp_dict[y][3]
            typ = exp_dict[y][4]
            attr = exp_dict[y][5]
            if item=="fact":
                addition = '(chunk goal("'+domain+'", rehearsed, 0, 5) decay INF of DECAY-TIME) ; \n'
                list_of_lines.insert(i, addition)
                i+=1
                addition = '(chunk a "'+cat+'" '+typ+' "'+attr+'" decay INF of DECAY-TIME) ; \n'
                list_of_lines.insert(i, addition)
            if item=="question":
                i-=1
        list_of_lines[i] = list_of_lines[i][:-4]
        list_of_lines[i+1] = '\n .\n'

        f = open("Maude-2/proj/cifma-2020-2.maude", "w")
        f.writelines(list_of_lines)
        f.close()
        subprocess.call("./start_maude.sh")

        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())


        f = open("Maude-2/proj/cifma-2020-2.maude", "r")
        f2 = open("Maude-2/proj/cifma-2020-help.maude", "w")
        start_str = 'eq initSemanticMem ='
        end_str = '.'
        for line in f:
            if start_str in line:
                break
            f2.write(line)
        for line in f:
            if end_str in line:
                f2.write("\n\n")
                break
        for line in f:
            f2.write(line)
        f.close()
        f2.close()

        f = open("Maude-2/proj/cifma-2020-help.maude", "r")
        f2 = open("Maude-2/proj/cifma-2020-2.maude", "w")
        start_str = 'eq init-STM ='
        end_str = ' .'
        for line in f:
            if start_str in line:
                break
            f2.write(line)
        for line in f:
            if end_str in line:
                f2.write("\n\n")
                break
        for line in f:
            f2.write(line)
        f.close()
        f2.close()

        f = open("Maude-2/proj/cifma-2020-2.maude", "r")
        f2 = open("Maude-2/proj/cifma-2020-help.maude", "w")
        start_str = 'eq init ='
        end_str = 'theHuman .'
        for line in f:
            if start_str in line:
                break
            f2.write(line)
        for line in f:
            if end_str in line:
                f2.write("\n\n")
                break
        for line in f:
            f2.write(line)
        f.close()
        f2.close()

        f = open("Maude-2/proj/cifma-2020-help.maude", "r")
        f2 = open("Maude-2/proj/cifma-2020-2.maude", "w")
        for line in f:
            f2.write(line)
        f.close()
        f2.close()


        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())

        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()

        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
                if (cat=="bird" or cat=="canary" or cat=="ostrich"):
                    domain = "Birds"
                elif (cat=="fish" or cat=="salmon" or cat=="shark"):
                    domain = "Fish"
                elif (cat=="animal"):
                    domain = "Animals"
                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')        
        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"))

