from math import inf

from ..Qt import QtWidgets, QtGui


class SciSpinBox(QtWidgets.QDoubleSpinBox):
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.validator = QtGui.QDoubleValidator(self)

        self.setMinimum(-inf)
        self.setMaximum(inf)
        self.setDecimals(1000)
        self.precision = 0.001

        self._prev_value = float(self.lineEdit().text())

    def valueFromText(self, text: str) -> float:
        try:
            self._prev_value = float(self.cleanText())
        except ValueError:
            pass
        return self._prev_value

    def textFromValue(self, value: float) -> str:
        if value == 0:
            return '0'
        else:
            return f'{value:.3e}'

    def stepBy(self, step: int):
        self._prev_value = self.value()

        new_value = self._prev_value
        if new_value != 0.0:
            new_value *= 10**(step/19.)
        else:
            new_value = 0.001

        self.setValue(new_value)
        self.lineEdit().setText(f'{new_value:.3e}')

    def validate(self, text, pos):
        return self.validator.validate(text, pos)
