import pyqtgraph as pg
from PyQt5.QtWidgets import QWidget, QTableWidget, QVBoxLayout, QTableWidgetItem, QLabel, QPushButton, QLineEdit, QHBoxLayout
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator


from src.utils.json_tools import read_json, write_json
from src.gui import qt_settings as qts

class settingsWindow(QWidget):
    def __init__(self, path: str, name: str, upd_func):
        super(settingsWindow, self).__init__()
        self._settingsPath = path
        self._name = name
        self._data = {}
        self._upd_func = upd_func

        self.load_settings()
        self._init_ui()

    def load_settings(self) -> None:
        self._data = read_json(self._settingsPath)

    def write_settings(self) -> None:
        write_json(self._settingsPath, self._data)
    
    def getParams(self) -> dict:
        return self._data

    
    def _init_ui(self) -> None:
        save_button = QPushButton()
        restore_button = QPushButton()
        save_button.setText("Save")
        restore_button.setText("Restore")
        self._num_points = QLineEdit()
        self._num_points.setPlaceholderText("Enter the number of welding points")
        self._num_points.setValidator(QIntValidator())
        control_layout = QHBoxLayout()
        control_layout.addWidget(save_button)
        control_layout.addWidget(restore_button)
        control_layout.addWidget(self._num_points)

        save_button.pressed.connect(self._save)
        restore_button.pressed.connect(self._restore)
        self._num_points.editingFinished.connect(self._expand)
        
        self._param_table = QTableWidget()
        self._param_table.setColumnCount(2)
        self._param_table.setRowCount(len(self._data))
        for i, (key, items) in enumerate(self._data.items()):
            self._param_table.setItem(i, 0, QTableWidgetItem(key))
            self._param_table.setItem(i, 1, QTableWidgetItem(str(items[0])))

        layout = QVBoxLayout()
        header = QLabel(self._name)
        layout.addWidget(header)
        layout.addLayout(control_layout)
        layout.addWidget(self._param_table)
        self.setLayout(layout)
        self.setStyleSheet(qts.white_style)
        #self.show()
        
    def _save(self) -> dict:
        self._data = {}
        for i in range(self._param_table.rowCount()):
            key = self._param_table.item(i, 0).text()
            data = []
            for j in range(1, self._param_table.columnCount()):
                param = self._param_table.item(i, j).text()
                if key != "trace_storage_path":
                    param = float(param)
                data.append(param)
            self._data[key] = data
        self.write_settings()
        self._upd_func()
        
    
    def _restore(self) -> None:
        self._param_table.setRowCount(len(self._data))
        self._param_table.setColumnCount(len(self._data[self._data.keys()[0]]))
        for i, (key, items) in enumerate(self._data.items()):
            self._param_table.setItem(i, 0, QTableWidgetItem(key))
            for j, item in enumerate(items):
                self._param_table.setItem(i, j+1, QTableWidgetItem(str(item)))
    
    def _expand(self) -> None:
        param=int(self._num_points.text())
        prev_columns = self._param_table.columnCount()
        self._param_table.setColumnCount(param+1)
        if prev_columns < param+1:
          for i in range(prev_columns, param+1):
            for j, (key, items) in enumerate(self._data.items()):
                self._param_table.setItem(j, i, QTableWidgetItem(str(items[-1])))




        


if __name__ == '__main__':
    app = pg.mkQApp("Parameter Tree Example")
    window = settingsWindow('params\operator_params.json', 'operator')
    app.exec()

    
