from silx.gui import qt

from orangecontrib.ewoks3dxrd.segment.base_segmenter_algo_view import (
    _BaseSegmenterAlgoView as BaseSegmenterAlgoView,
)
from orangecontrib.ewoks3dxrd.segment.gaussian_segmenter_param_view import (
    GaussianPeakSearchParamView,
)
from orangecontrib.ewoks3dxrd.segment.lima_segmenter_param_view import (
    LimaSegmenterParamView,
)
from orangecontrib.ewoks3dxrd.segmenter_frame import OWFrameSegmenter

ALGORITHMS: list[str] = [
    "gaussian_peak_search",
    "lima_segmenter",
]

VIEWS: list[type[BaseSegmenterAlgoView]] = [
    GaussianPeakSearchParamView,
    LimaSegmenterParamView,
]


def _set_and_assert_segmenter(
    widget: OWFrameSegmenter, index: int = 0, list_index: int = 0
):
    group = widget._inputParametersBox._segmenter_group
    group._algoSelector.setCurrentIndex(index)
    qt.QApplication.instance().processEvents()

    assert group._algoSelector.currentIndex() == index
    assert group._stackedViewsWidget.currentIndex() == index

    assert group._algoSelector.currentText() == ALGORITHMS[list_index]
    current_view = group.currentView
    assert isinstance(current_view, VIEWS[list_index])


def test_segmenter_view_switch(qtapp):
    widget = OWFrameSegmenter()
    segmenter_group = widget._inputParametersBox._segmenter_group

    for i, algo_name in enumerate(ALGORITHMS):
        index = segmenter_group._algoSelector.findText(algo_name)
        assert index != -1, f"Algorithm {algo_name} not found in ComboBox items."
        _set_and_assert_segmenter(widget=widget, index=index, list_index=i)

    index = segmenter_group._algoSelector.findText(ALGORITHMS[0])
    _set_and_assert_segmenter(widget=widget, index=index, list_index=0)
