from silx.gui import qt

from ..common.base_parameter_control import BaseParameterControl
from ..common.dataURL_group_box import DataURLGroupBox
from ..common.master_file_widget import MasterFileWidget
from ..segment.folder_metadata_group_box import SampleConfigGroupBox
from .grain_map_parameter_group_box import GrainMapParameterGroupBox


class MakeMapControlBox(BaseParameterControl):
    sigGrainUrlChanged = qt.Signal()
    sigStrongPeaksUrlChanged = qt.Signal()
    sigFinePeaksUrlChanged = qt.Signal()

    def __init__(self, parent=None):
        super().__init__(title="Refine Grains Settings", parent=parent)
        self.grainMapParameterGroup = GrainMapParameterGroupBox(self)
        self.sampleConfigGroup = SampleConfigGroupBox(parent=self)
        self.latticeFile = MasterFileWidget("Select Lattice File")
        self.latticeFile.setAutoDefault(False)
        self.latticeFile.setNameFilters(
            ["Par Files (*.par)", "CIF Files (*.cif)", "JSON Files (*.json)"]
        )

        self.inputGrainUrl = DataURLGroupBox(title="Input Grain Data URL")
        self.inputStrongPeaksUrl = DataURLGroupBox(title="Strong Filtered Peaks URL")

        self.finePeaksUrl = DataURLGroupBox(title="Use finely filtered peaks")
        self.finePeaksUrl.setCheckable(True)
        self.finePeaksUrl.setChecked(False)
        self.finePeaksUrl.setToolTip(
            "Use all peaks aligned with lattice rings to validate grains. Otherwise, grains are refined using only strongly filtered peaks."
        )

        self.inputGrainUrl.editingFinished.connect(self.sigGrainUrlChanged)
        self.inputStrongPeaksUrl.editingFinished.connect(self.sigStrongPeaksUrlChanged)
        self.finePeaksUrl.editingFinished.connect(self.sigFinePeaksUrlChanged)

        self.settingsLayout.addWidget(self.grainMapParameterGroup)
        self.settingsLayout.addWidget(self.sampleConfigGroup)

        latticeWidget = qt.QWidget()
        latticeLayout = qt.QFormLayout(latticeWidget)
        latticeLayout.addRow("Lattice File", self.latticeFile)
        self.settingsLayout.addWidget(latticeWidget)
        self.settingsLayout.addWidget(self.inputGrainUrl)
        self.settingsLayout.addWidget(self.inputStrongPeaksUrl)
        self.settingsLayout.addWidget(self.finePeaksUrl)

    def getGrainURL(self) -> str:
        return self.inputGrainUrl.text()

    def setGrainURL(self, url: str):
        self.inputGrainUrl.setText(url)

    def getFinePeaksURL(self) -> str:
        return self.finePeaksUrl.text()

    def setFinePeaksURL(self, url: str):
        return self.finePeaksUrl.setText(url)

    def getStrongPeaksURL(self) -> str:
        return self.inputStrongPeaksUrl.text()

    def setStrongPeaksURL(self, url: str):
        return self.inputStrongPeaksUrl.setText(url)

    def validate(self):
        if self.sampleConfigGroup.getSampleConfig() is None:
            raise ValueError("Sample Config not valid")
        url = self.inputGrainUrl.validDataURL()
        if not url:
            message = "The Grain Input Data URL is empty. Please provide a path."
        elif not self.inputGrainUrl.validDataURL():
            message = f"The grain data group '{url}' does not exist."
        else:
            message = None

        url = self.inputStrongPeaksUrl.validDataURL()
        if not url:
            message = "The Strong Peaks Input Data URL is empty. Please provide a path."
        elif not self.inputStrongPeaksUrl.validDataURL():
            message = f"The Strong Peaks data group '{url}' does not exist."
        else:
            message = None

        if self.finePeaksUrl.isChecked():
            url = self.finePeaksUrl.validDataURL()
            if not url:
                message = "The Fine Peaks Input Data URL is empty. Please provide a path or uncheck it."
            elif not self.finePeaksUrl.validDataURL():
                message = f"The Fine Peaks data group '{url}' does not exist."
            else:
                message = None

        if message:
            raise ValueError(f"Invalid Inputs, {message}")
