import sys

from PySide6.QtGui import QStandardItemModel, QStandardItem
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication, QFileDialog
from PySide6.QtCore import QFile, QIODevice, QModelIndex, QAbstractTableModel
from abacus_core import AbacusCore


class AbacusGUI:

    def __init__(self):
        self._abacus_core = AbacusCore()
        self._step = 0
        self._history = []
        self._app = QApplication(sys.argv)
        ui_file_name = "gui.ui"
        ui_file = QFile(ui_file_name)
        if not ui_file.open(QIODevice.ReadOnly):
            print(f"Cannot open {ui_file_name}: {ui_file.errorString()}")
            sys.exit(-1)
        loader = QUiLoader()
        self._window = loader.load(ui_file)
        ui_file.close()
        if not self._window:
            print(loader.errorString())
            sys.exit(-1)
        self._window.show()
        self._window.but_enter.clicked.connect(self._berechne)
        self._window.le_input.returnPressed.connect(self._berechne)
        self._history_model = QStandardItemModel()
        self._window.lv_history.setModel(self._history_model)
        self._var_model = QStandardItemModel()
        self._func_model = QStandardItemModel()
        self._window.lv_variable.setModel(self._var_model)
        self._window.lv_func.setModel(self._func_model)
        # self._window.actionExit.clicked.connect(self._berechne)
        self._check_models()
        sys.exit(self._app.exec())

    def _berechne(self):
        self._step += 1
        input_str = self._window.le_input.text()
        result = self._abacus_core.parse_input(input_str)
        if result:
            self._history.append(result)
            input_str = result[0]
            input_wo_var = str(result[1])
            ergebnis = str(result[2])
            comment = result[3]
            res_str = str(self._step) + '. ' + input_str + ' = ' + ergebnis
            # res_str = str(self._step) + '. ' + input_str + ' => ' + input_wo_var + ' = ' + ergebnis
            if comment:
                res_str += ' ' + comment
            item = QStandardItem(res_str)
            self._history_model.appendRow(item)
            res = result[2]
            self._window.le_input.setText(str(res))
        else:
            self._window.le_input.setText('')
        self._check_models()

    def _check_models(self):
        self._var_model.clear()
        self._func_model.clear()
        for k, v in self._abacus_core.get_vars().items():
            item = QStandardItem(k+' = '+str(v))
            self._var_model.appendRow(item)
        for k, v in self._abacus_core.get_funcs().items():
            item = QStandardItem(k+' = '+str(v))
            self._func_model.appendRow(item)


if __name__ == "__main__":
    ag = AbacusGUI()

