from __future__ import annotations

from typing import TYPE_CHECKING

from qtpy.QtCore import Qt
from superqt import QEnumComboBox

from napari._qt.layer_controls.dynamic.widgets.qt_widget_controls_base import (
    QtWidgetControlsBase,
    QtWrappedLabel,
)
from napari._qt.utils import qt_signals_blocked
from napari.layers.vectors._vectors_constants import VectorStyle
from napari.utils.events.event_utils import connect_setattr

if TYPE_CHECKING:
    from qtpy.QtWidgets import QWidget

    from napari.layers import Vectors


class QtVectorStyleComboBoxControl(QtWidgetControlsBase):
    """
    Class that wraps the connection of events/signals between the layer vector style
    value attribute and Qt widgets.

    Parameters
    ----------
    parent: qtpy.QtWidgets.QWidget
        An instance of QWidget that will be used as widgets parent
    layers : list[napari.layers.Vectors]
        A list of napari Vectors layers.

    Attributes
    ----------
    vector_style_combobox : qtpy.QtWidgets.QComboBox
        Dropdown widget to select vector_style for the vectors.
    vector_style_combobox_label : napari._qt.layer_controls.widgets.qt_widget_controls_base.QtWrappedLabel
        Label for vector_style value chooser widget.
    """

    _layers: list[Vectors]

    def __init__(
        self, layers: list[Vectors], parent: QWidget | None = None
    ) -> None:
        super().__init__(layers, parent)
        # Setup layer
        for layer in self._layers:
            layer.events.vector_style.connect(self._on_vector_style_change)

        # Setup widgets
        # dropdown to select the edge display vector_style
        vector_style_combobox = QEnumComboBox(parent, VectorStyle)
        vector_style_combobox.setCurrentEnum(
            VectorStyle(self._layers[0].vector_style)
        )
        self.vector_style_combobox = vector_style_combobox
        for layer in self._layers:
            connect_setattr(
                self.vector_style_combobox.currentEnumChanged,
                layer,
                'vector_style',
            )

        self.vector_style_combobox_label = QtWrappedLabel('vector style:')

    def _on_vector_style_change(self) -> None:
        """Receive layer model vector style change event & update dropdown."""
        with qt_signals_blocked(self.vector_style_combobox):
            vector_style = self._layers[0].vector_style
            index = self.vector_style_combobox.findText(
                vector_style, Qt.MatchFlag.MatchFixedString
            )
            self.vector_style_combobox.setCurrentIndex(index)

    def get_widget_controls(self) -> list[tuple[QtWrappedLabel, QWidget]]:
        return [(self.vector_style_combobox_label, self.vector_style_combobox)]
