from __future__ import annotations

from silx.gui import qt

from ewoks3dxrd.models import GaussianPeakSearchConfig
from ewoks3dxrd.models import LimaSegmenterAlgoConfig
from ewoks3dxrd.models import SegmenterConfig

from ..common.collapsible_widget import CollapsibleWidget
from .base_segmenter_algo_view import _BaseSegmenterAlgoView as BaseSegmenterAlgoView
from .gaussian_segmenter_param_view import GaussianPeakSearchParamView
from .lima_segmenter_param_view import LimaSegmenterParamView


class SegmenterParamGroupBox(CollapsibleWidget):
    sigParamsChanged = qt.Signal()

    ALGORITHMS: list[str] = [
        GaussianPeakSearchConfig.model_fields["algorithm"].default,
        LimaSegmenterAlgoConfig.model_fields["algorithm"].default,
    ]

    def __init__(self, parent: qt.QWidget | None = None, **kwargs) -> None:
        super().__init__("Segmentation Parameters", parent=parent, **kwargs)

        mainLayout = qt.QVBoxLayout()
        self.setLayout(mainLayout)
        self._algoSelector = qt.QComboBox(self)
        self._algoSelector.addItems(self.ALGORITHMS)
        self._algoSelector.currentIndexChanged.connect(self._handleAlgorithmChange)
        mainLayout.addWidget(self._algoSelector)

        self._stackedViewsWidget = qt.QStackedWidget()
        self._views = [
            GaussianPeakSearchParamView(self),
            LimaSegmenterParamView(self),
        ]

        for view in self._views:
            self._stackedViewsWidget.addWidget(view)
            view.sigParamsChanged.connect(self.sigParamsChanged)

        mainLayout.addWidget(self._stackedViewsWidget)

    @property
    def currentView(self) -> BaseSegmenterAlgoView:
        return self._views[self._stackedViewsWidget.currentIndex()]

    def getConfig(self) -> SegmenterConfig | None:
        return self.currentView.getConfig()

    def setConfig(self, config: SegmenterConfig):
        if config.algorithm in self.ALGORITHMS:
            index = self.ALGORITHMS.index(config.algorithm)
            self._algoSelector.setCurrentIndex(index)
            self.currentView.setConfig(config)

    def _handleAlgorithmChange(self, index: int):
        self._stackedViewsWidget.setCurrentIndex(index)
        self.sigParamsChanged.emit()
