from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QSplitter, QWidget

from openlog.gui.assay_visualization.assay_plot_widget import AssayDomainType


class DiagramsMaker:
    def __init__(self, plot_widget) -> None:
        """
        Generic class containing methods to plot and add diagrams in PlotWidgetContainer.
        Give access to container and main PlotWidget.
        Args:
            - container: PlotWidgetContainer instance
        """
        container = plot_widget.get_container()
        self.container = container
        self.main = plot_widget
        self.plotItem = container.plotItem
        self.data = None
        # list of displayed widgets
        self.diagram_list = []
        # splitter to contains widgets. To be added to PlotWidgetContainer
        self.splitter = None
        # splitter index in PlotWidgetContainer
        self.index = None

    def display_diagram_list(self):

        for diagram in self.diagram_list:

            self.splitter.addWidget(diagram)

        if self.index is None:
            self.container.addWidget(self.splitter)
            self.index = self.container.indexOf(self.splitter)
        else:
            self.container.insertWidget(self.index, self.splitter)

    def _set_vertical_splitter(self):

        self.splitter = QSplitter(self.container)
        self.splitter.setOrientation(
            Qt.Vertical if self.main.domain == AssayDomainType.DEPTH else Qt.Horizontal
        )
        self.splitter.setChildrenCollapsible(False)

    def clear_diagrams(self):

        self.diagram_list.clear()

        if not self.splitter:
            return

        while self.splitter.count():
            self.splitter.widget(0).deleteLater()
            self.splitter.widget(0).setParent(None)

        self.splitter.deleteLater()
        self.splitter.setParent(None)
        self.splitter = None

    def _get_diagram(self) -> QWidget:
        """
        Create one diagram. Should be called in `set_diagrams` method
        """
        return NotImplementedError

    def set_diagrams(self):
        """
        Create one or multiple diagrams.
        """
        # update container
        self.container = self.main.get_container()

    def attach_diagrams(self):
        """
        Put diagrams in PlotWidgetContainer.
        """
        # update container
        self.container = self.main.get_container()
        if self.splitter:
            self.container.addWidget(self.splitter)

    def dettach_diagrams(self):
        """
        Remove diagrams from PlotWidgetContainer.
        """
        if self.splitter:
            self.splitter.setParent(None)

    def update_main_plot(self):
        """
        Slot designed to be connected to a diagram signal, should act on main plot of PlotWidgetContainer
        """
        pass

    def update_diagram(self):
        """
        Slot designed to be connected to main plot signal.
        """
        pass
