from qgis.PyQt.QtGui import QColor

from openlog.gui.assay_visualization.config.config_saver import ConfigSaver
from openlog.gui.assay_visualization.config.config_saver_utils import (
    deserialize_pen_param,
    serialize_pen_param,
)


class DiscreteCategoricalSaver(ConfigSaver):
    def _serialize(self, config):

        d = super()._serialize(config)
        # point symbology
        d["point_symbol"] = config.symbol_parameter.value()
        d["point_size"] = config.symbol_size_parameter.value()
        qcolor = config.symbol_color_parameter.value()
        d["point_color"] = qcolor.name()

        # categories
        d["point_symbology"] = config.point_symbology.to_dict()

        return d

    def _deserialize(self, config, dict):

        # points
        config.symbol_parameter.setValue(dict.get("point_symbol"))
        config.symbol_size_parameter.setValue(dict.get("point_size"))
        qcolor = QColor()
        qcolor.setNamedColor(dict.get("point_color"))
        config.symbol_color_parameter.setValue(qcolor)

        # categories
        config.point_symbology = config.point_symbology.from_json(
            dict.get("point_symbology")
        )
        if config.plot_item:
            config.plot_item.set_symbology(config.point_symbology)


class ExtendedCategoricalSaver(ConfigSaver):
    def _serialize(self, config):

        d = super()._serialize(config)
        # bar pen
        d |= serialize_pen_param(config, "pen_params", "bar_pen")
        # text color
        d["text_color"] = config.text_color_param.value().name()
        # categories
        d["bar_symbology"] = config.bar_symbology.to_dict()

        return d

    def _deserialize(self, config, dict):

        # bar pen
        deserialize_pen_param(config, dict, "pen_params", "bar_pen")
        if config.text_bar_graph_item is not None:
            config.text_bar_graph_item.setPen(config.pen_params.get_pen())
        # text color
        qcolor = QColor()
        qcolor.setNamedColor(dict.get("text_color"))
        config.text_color_param.setValue(qcolor)
        # categories
        config.bar_symbology = config.bar_symbology.from_json(dict.get("bar_symbology"))
        if config.plot_item:
            config.plot_item.set_symbology(config.bar_symbology)
