from silx.gui import qt

from ..common.base_parameter_control import BaseParameterControl
from ..geometry.geometry_transformation_settings import GeometryTransformationSettings
from ..lattice.lattice_parameters import LatticeParameters


class GeometryControlBox(BaseParameterControl):
    def __init__(self, parent=None):
        super().__init__(title="G-Vector Computation", parent=parent)

        _scrollArea = qt.QScrollArea()
        _scrollArea.setWidgetResizable(True)
        _scrollArea.setFrameShape(qt.QFrame.NoFrame)
        _scrollArea.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding)

        _scrollContent = qt.QWidget()
        _scrollLayout = qt.QVBoxLayout(_scrollContent)
        _scrollLayout.setContentsMargins(0, 0, 0, 0)

        self.geometryPanel = GeometryTransformationSettings(self)
        self.latticeGroup = LatticeParameters("Show lattice rings", self)
        self.latticeGroup.setCheckable(True)

        _scrollLayout.addWidget(self.geometryPanel)
        _scrollLayout.addWidget(self.latticeGroup)
        _scrollLayout.addStretch(1)

        _scrollArea.setWidget(_scrollContent)
        layout = self.layout()
        index = layout.indexOf(self.settingsGroup)
        layout.takeAt(index)
        self.settingsGroup.deleteLater()

        layout.insertWidget(index, _scrollArea)
        layout.setStretch(0, 1)
        layout.setStretch(1, 0)

    def getGeometryParameters(self):
        return self.geometryPanel.getGeometryParameters()

    def setGeometryFile(self, path):
        self.geometryPanel.setGeometryFile(path)

    def validate(self):
        parameters = self.geometryPanel.getGeometryParameters()
        if parameters["distance"] == 0.0 or parameters["wavelength"] == 0.0:
            raise ValueError(
                """Check Geometry Settings: 
                Distance/Wavelength cannot be zero. Please provide a positive value.
            """
            )
