import os

import pyqtgraph.parametertree as ptree
from qgis.core import QgsApplication
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QWidget

from openlog.__about__ import DIR_PLUGIN_ROOT
from openlog.gui.assay_visualization.stacked.stacked_config import StackedConfiguration


class StackedConfigWidget(QWidget):
    def __init__(self, parent: QWidget = None):
        """
        Widget for StackedConfiguration display and edition.
        User can change assay columns configuration.

        Args:
            parent: parent object
        """
        super().__init__(parent)
        self.setMinimumWidth(300)

        uic.loadUi(
            os.path.join(os.path.dirname(__file__), "stacked_config_widget.ui"),
            self,
        )

        self.stacked_config = None

        # Add parameter tree
        self.parameter_tree = ptree.ParameterTree(self)
        self.param_layout.addWidget(self.parameter_tree)

        self.check_all_button.clicked.connect(self.check_all)
        self.uncheck_all_button.clicked.connect(self.uncheck_all)
        self.collapse_button.setIcon(QIcon(QgsApplication.iconPath("mIconExpand.svg")))
        self.collapse_button.setText("")
        self.collapse_button.setToolTip("Collapse all")
        self.collapse_button.clicked.connect(self.collapse)

        self.uncheck_all_button.setText("")
        self.uncheck_all_button.setToolTip("Uncheck all")
        self.uncheck_all_button.setIcon(
            QIcon(
                str(DIR_PLUGIN_ROOT / "resources" / "images" / "icon_uncheck_all.svg")
            )
        )

        self.check_all_button.setText("")
        self.check_all_button.setToolTip("Check all")
        self.check_all_button.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources" / "images" / "icon_check_all.svg"))
        )

    def set_stacked_config(self, stacked_config: StackedConfiguration) -> None:
        """
        Define parameter for a stacked configuration

        Args:
            stacked_config: (StackedConfiguration)
        """
        self.stacked_config = stacked_config

        self.stacked_label_values.setText(stacked_config.name)

        self.parameter_tree.clear()

        # Define params for all assay column
        all_params = ptree.Parameter.create(name="Columns", type="group")

        for param in stacked_config.get_pyqtgraph_params():
            all_params.addChild(param)

        for config in stacked_config.config_list:

            all_params.addChild(config.get_pyqtgraph_param())

        # set one transformation group to control global plot options
        if stacked_config.global_param is None:
            stacked_config.set_global_param()
            stacked_config.update_global_param()
        global_param = stacked_config.global_param

        all_params.insertChild(0, global_param)

        self.parameter_tree.setParameters(all_params, showTop=False)

        for config in stacked_config.config_list:
            for w in config.create_configuration_widgets(self):
                self.param_layout.addWidget(w)

    def check_all(self) -> None:
        """
        Check all visibility parameters for displayed configuration

        """
        self._check_all(True)

    def uncheck_all(self) -> None:
        """
        Uncheck all visibility parameters for displayed configuration

        """
        self._check_all(False)

    def _check_all(self, checked: bool) -> None:
        """
        Check or uncheck all visibility parameters for displayed configuration

        Args:
            checked: (bool) visibility parameter value
        """
        for assay_column_config in self.stacked_config.config_list:
            assay_column_config.visibility_param.setValue(checked)

    def collapse(self) -> None:
        """
        Collapse all visibility parameters

        """
        for assay_column_config in self.stacked_config.config_list:
            assay_column_config.visibility_param.setOpts(syncExpanded=True)
            assay_column_config.visibility_param.setOpts(expanded=False)

        # apply to global plot options
        if self.stacked_config.global_param:
            self.stacked_config.global_param.setOpts(syncExpanded=True)
            self.stacked_config.global_param.setOpts(expanded=False)
