from qgis.PyQt import QtWidgets

from qgis.core import (
    QgsProcessingUtils,
    QgsVectorLayer,
)
from qgis.utils import iface
from processing.gui.wrappers import (
    WidgetWrapper,
    DIALOG_STANDARD,
)
from processing.tools import dataobjects

from PreCourlis.widgets.interpolation_areas_config_dialog import (
    InterpolationAreasConfigDialog,
)


class InterpolationAreasWidgetWrapper(WidgetWrapper):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.context = dataobjects.createContext()
        self.parent_layer_widget_wrapper = None
        self.interpolation_areas_dialog = None

    def createWidget(self):
        button = QtWidgets.QPushButton(
            self.tr("Configure interpolation areas"), self.dialog
        )
        button.clicked.connect(self.openDialog)
        return button

    def postInitialize(self, wrappers):
        if self.dialogType != DIALOG_STANDARD:
            return

        for wrapper in wrappers:
            if wrapper.parameterDefinition().name() == self.param.parent_layer:
                self.parent_layer_widget_wrapper = wrapper

    def openDialog(self):
        string = self.parent_layer_widget_wrapper.parameterValue()
        layer = QgsProcessingUtils.mapLayerFromString(
            string, self.context, allowLoadingNewLayers=False
        )
        if not isinstance(layer, QgsVectorLayer):
            raise Exception(
                "Only vector layers are supported for interpolation areas configuration."
            )

        self.interpolation_areas_dialog = InterpolationAreasConfigDialog(
            iface.mainWindow()
        )
        self.interpolation_areas_dialog.set_layer(layer)
        self.interpolation_areas_dialog.exec_()
        self.interpolation_areas_dialog = None

    def setValue(self, value):
        pass

    def value(self):
        return None
