from __future__ import annotations

from typing import TYPE_CHECKING

from qtpy.QtWidgets import (
    QCheckBox,
    QWidget,
)

from napari._qt.layer_controls.dynamic.widgets.qt_widget_controls_base import (
    QtWidgetControlsBase,
    QtWrappedLabel,
)
from napari._qt.utils import attr_to_settr, checked_to_bool
from napari.utils.events.event_utils import connect_setattr

if TYPE_CHECKING:
    from napari.layers import Labels


class QtContiguousCheckBoxControl(QtWidgetControlsBase):
    """
    Class that wraps the connection of events/signals between the layer contiguous
    attribute and Qt widgets.

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

    Attributes
    ----------
    contiguous_checkbox : qtpy.QtWidgets.QCheckBox
        Checkbox to control if label layer is contiguous.
    contiguous_checkbox_label : napari._qt.layer_controls.widgets.qt_widget_controls_base.QtWrappedLabel
        Label for the contiguous model chooser widget.
    """

    _layers: list[Labels]

    def __init__(
        self, layers: list[Labels], parent: QWidget | None = None
    ) -> None:
        super().__init__(layers, parent)
        # Setup widgets
        self._layers = layers

        contig_cb = QCheckBox()
        contig_cb.setToolTip('Contiguous editing')
        contig_cb.setChecked(self._layers[0].contiguous)

        self._callbacks.append(
            attr_to_settr(
                self._layers[0],
                'contiguous',
                contig_cb,
                'setChecked',
            )
        )
        for layer in self._layers:
            connect_setattr(
                contig_cb.stateChanged,
                layer,
                'contiguous',
                convert_fun=checked_to_bool,
            )
        self.contiguous_checkbox = contig_cb

        self.contiguous_checkbox_label = QtWrappedLabel('contiguous:')

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