from ..Qt import QtWidgets, QtGui, QtCore
from ..lib.iconloading import get_icon
from ..lib.pg_objects import RegionItem


class FitToolbar(QtWidgets.QToolBar):
    def __init__(
            self,
            fitaction: QtWidgets.QAction,
            limit_menu: QtWidgets.QMenu,
            parent=None,
    ):
        super().__init__('Fit', parent=parent)

        self.fit_action = fitaction
        self.region = RegionItem()
        self.addAction(fitaction)

        self.fitlim_button = QtWidgets.QToolButton(self)
        self.fitlim_button.setMenu(limit_menu)
        self.fitlim_button.setPopupMode(self.fitlim_button.InstantPopup)
        self.fitlim_button.setIcon(get_icon('fit_region'))
        self.addWidget(self.fitlim_button)

        self.label = QtWidgets.QLabel(self)
        self.label.setText('L: ')
        self.addWidget(self.label)
        self.label.setEnabled(False)

        self.lineedit = QtWidgets.QLineEdit(self)
        self.lineedit.setValidator(QtGui.QDoubleValidator())
        self.lineedit.setMaximumWidth(92)
        self.addWidget(self.lineedit)
        self.lineedit.setEnabled(False)

        self.label2 = QtWidgets.QLabel(self)
        self.label2.setText(' R: ')
        self.addWidget(self.label2)
        self.label2.setEnabled(False)

        self.lineedit2 = QtWidgets.QLineEdit(self)
        self.lineedit2.setValidator(QtGui.QDoubleValidator())
        self.addWidget(self.lineedit2)
        self.lineedit2.setMaximumWidth(92)
        self.lineedit2.setEnabled(False)

        self.limit_group = QtWidgets.QActionGroup(self)
        for ac in limit_menu.actions():
            self.limit_group.addAction(ac)

        self.limit_group.triggered.connect(self.change_limit_type)

        self.region.sigRegionChanged.connect(self.change_labels)
        self.change_labels()

        self.lineedit.textChanged.connect(self.move_region)
        self.lineedit2.textChanged.connect(self.move_region)

    @QtCore.pyqtSlot(QtWidgets.QAction)
    def change_limit_type(self, action: QtWidgets.QAction):
        is_custom = (action.text() in ['Custom', 'Exclude region'])
        print(is_custom)

        for w in [self.label, self.label2, self.lineedit, self.lineedit2]:
            w.setEnabled(is_custom)

    def change_labels(self):
        r = self.region.getRegion()
        self.lineedit.blockSignals(True)
        self.lineedit.setText(f'{r[0]:.4g}')
        self.lineedit.blockSignals(False)

        self.lineedit2.blockSignals(True)
        self.lineedit2.setText(f'{r[1]:.4g}')
        self.lineedit2.blockSignals(False)

    def move_region(self):
        try:
            r_min = float(self.lineedit.text())
        except ValueError:
            r_min = None

        try:
            r_max = float(self.lineedit2.text())
        except ValueError:
            r_max = None

        if r_min is not None and r_max is not None:
            self.region.setRegion((r_min, r_max), use_log=True)

    def get_limit(self):
        action_text = self.limit_group.checkedAction().text()

        return {
            'None': 'none',
            'Visible x range': 'x',
            'Custom': ('in', self.region.getRegion()),
            'Exclude region': ('out', self.region.getRegion()),
        }[action_text]
