from __future__ import annotations

from silx.gui import qt
from silx.gui.plot.actions.control import XAxisLogarithmicAction
from silx.gui.plot.actions.control import YAxisLogarithmicAction
from silx.gui.utils import blockSignals


class _AxesComboBox(qt.QComboBox):
    def __init__(self, defaultAxis: str, parent: qt.QWidget | None = None):
        super().__init__(parent)
        self._defaultAxis = defaultAxis

    def getSelectedAxis(self) -> str:
        return self.currentText() if self.currentText() else self._defaultAxis

    def populateAxes(self, axisNames: tuple[str, ...], defaultAxis: str | None = None):
        if defaultAxis is not None:
            self._defaultAxis = defaultAxis

        with blockSignals(self):
            self.clear()
            self.addItems(axisNames)
            if self._defaultAxis:
                self.setCurrentText(self._defaultAxis)


class AxisControlToolbar(qt.QToolBar):
    sigAxisChanged = qt.Signal()

    def __init__(self, parent=None, plot=None):
        super().__init__(parent)

        self._xAxisComboBox = _AxesComboBox(parent=self, defaultAxis="s_raw")
        self._yAxisComboBox = _AxesComboBox(parent=self, defaultAxis="f_raw")
        self.addAction(XAxisLogarithmicAction(parent=self, plot=plot))
        self.addAction(YAxisLogarithmicAction(parent=self, plot=plot))
        self._xAxisComboBox.currentTextChanged.connect(self.sigAxisChanged.emit)
        self._yAxisComboBox.currentTextChanged.connect(self.sigAxisChanged.emit)
        self.addWidget(qt.QLabel("X-axis"))
        self.addWidget(self._xAxisComboBox)
        self.addWidget(qt.QLabel("Y-axis"))
        self.addWidget(self._yAxisComboBox)

    def populateAxes(self, axisNames: tuple[str, ...], defaultX: str, defaultY: str):
        self._xAxisComboBox.populateAxes(axisNames=axisNames, defaultAxis=defaultX)
        self._yAxisComboBox.populateAxes(axisNames=axisNames, defaultAxis=defaultY)

    def getSelectedX(self) -> str:
        return self._xAxisComboBox.getSelectedAxis()

    def getSelectedY(self) -> str:
        return self._yAxisComboBox.getSelectedAxis()
