from typing import Any

import pyqtgraph as pg
import pyqtgraph.parametertree as ptree
import pyqtgraph.parametertree.parameterTypes as pTypes

from openlog.gui.assay_visualization.config import json_utils
from openlog.gui.assay_visualization.config.assay_column_visualization_config import (
    AssayColumnVisualizationConfig,
)


class ExtendedAssayColumnVisualizationConfig(AssayColumnVisualizationConfig):
    def __init__(self, column: str):
        """
        Store visualization configuration for an extended assay column.
        Can also access plot item if configuration created from visualization widget

        Configuration supported :
        - visibility_param (bool) : assay column visibility (default : True)
        - pen_params (QPen) : assay column pen (default : black)
        - bar_color_param (QColor): assay column bar color (default : white)

        Args:
            column: (str) assay column name
        """
        super().__init__(column)
        self.pen_params.setName(self.tr("Bar pen"))
        self.bar_color_param = pTypes.ColorParameter(
            name=self.tr("Bar fill"), value="white", default="white"
        )

    def from_json(self, data: dict) -> None:
        """
        Define ExtendedAssayColumnVisualizationConfig from json data (see to_dict)

        Args:
            data: json data

        """
        super().from_json(data)

        # Bar color
        self.bar_color_param.setValue(json_utils.color_from_json(data["bar_color"]))

    def to_dict(self) -> dict:
        """
        Convert configuration to dict (use for json export)

        Returns:
            dict: configuration as dict

        """
        result = super().to_dict()

        # Bar color
        result["bar_color"] = json_utils.color_to_dict(self.bar_color_param.value())

        return result

    def set_plot_item(self, plot_item: pg.PlotDataItem) -> None:
        """
        Define plot item containing current assay data

        Args:
            plot_item: pg.PlotDataItem
        """
        super().set_plot_item(plot_item)
        if self.plot_item:
            # Define current parameters
            self.plot_item.setBrush(self.bar_color_param.value())

            # Connection to parameter changes
            self.bar_color_param.sigValueChanged.connect(
                lambda params, changes: self.plot_item.setBrush(changes)
            )

    def add_children_to_root_param(self, params: ptree.Parameter):
        super().add_children_to_root_param(params)
        params.addChild(self.bar_color_param)

    def copy_from_config(self, other) -> None:
        """
        Copy configuration from another configuration.
        If a plot item is associated it will be updated

        Args:
            other: configuration to be copy
        """
        super().copy_from_config(other)
        self.pen_params.setValue(other.pen_params.pen)
        self.bar_color_param.setValue(other.bar_color_param.value())
