import pyqtgraph as pg
from pyqtgraph.Qt import QtWidgets
from pyqtgraph.parametertree import Parameter, ParameterTree

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

class settingsWindow(QtWidgets.QWidget):
    def __init__(self, path: str, name: str, upd_func):
        super(settingsWindow, self).__init__()
        self.settingsPath = path
        self.name = name
        
        self.data = {}
        self.params = None
        self.load_settings()
        self._init_ui()
        self.params.sigTreeStateChanged.connect(upd_func)

    def load_settings(self):
        self.data = read_json(self.settingsPath)

    def write_settings(self):
        self.getParams()
        write_json(self.settingsPath, self.data)

    def _getTreeStructure(self) -> list:
        params = []
        for key, value in self.data.items():
            params.append({'name': str(key), 'type': type(value).__name__, 'value': value})
        params.append({'name': 'Save', 'type': 'action'})
        return params
    
    def _init_ui(self):
        temp = self._getTreeStructure()
        self.params = Parameter.create(name=self.name, type='group', children=temp)
        self.params.param('Save').sigActivated.connect(self.write_settings)

        ParamsTree = ParameterTree()
        ParamsTree.setParameters(self.params, showTop=True)
        layout = QtWidgets.QGridLayout()
        layout.addWidget(ParamsTree, 0,0)
        self.setLayout(layout)
        self.setStyleSheet(qts.white_style)
       # self.show()
        
    def getParams(self) -> dict:
        self.data = {}
        for p in self.params:
            if p.name() != 'Save':
                self.data[p.name()] = p.value()
        return self.data

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

    
