from typing import Any
from PySide6 import QtWidgets, QtGui
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QTreeWidgetItem

from .qt.datalogger_ui import Ui_DataLogger


class QDataLogger(QtWidgets.QWidget, Ui_DataLogger):
    def __init__(self, parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.setupUi(self)

    def update_from_dict(self, data: dict[str, Any]) -> None:
        """Update the tree view with data from a dict.

        Args:
            data: Data to show.
        """
        self.treeWidget.clear()
        self._tree_from_dict(data=data, parent=self.treeWidget)
        self.treeWidget.expandAll()
        self.treeWidget.resizeColumnToContents(0)
        self.treeWidget.sortItems(0, Qt.AscendingOrder)

    def _tree_from_dict(self, data: dict[str, Any], parent=None):
        """Creates QTreeWidget from a python dict.

        Args:
            data: Data to show.
            parent: Parent item.
        """
        for key, value in data.items():
            item = QTreeWidgetItem(parent)
            item.setText(0, key)
            if isinstance(value, dict):
                self._tree_from_dict(data=value, parent=item)
            elif isinstance(value, list):
                [self._tree_from_dict(i, parent=item) for idx, i in enumerate(value)]

            else:
                item.setText(1, value)
                if value == "FALSE":
                    item.setForeground(1, QtGui.QBrush(QtGui.QColor("red")))
                if value == "TRUE":
                    item.setForeground(1, QtGui.QBrush(QtGui.QColor("lime")))
