# standard

# PyQGIS
from qgis.PyQt.QtWidgets import QHBoxLayout, QLayout, QWidget

# project
from oslandia.gui.commons.lbl_tag import Tag, TagLabel


class TagListWidget(QWidget):
    def __init__(self, parent: QWidget | None = None):
        """Widget to display a list of tag as text with text and background color

        :param parent: parent widget, defaults to None
        :type parent: QWidget | None, optional
        """
        super().__init__(parent)

        self.h_layout = QHBoxLayout()
        self.h_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.h_layout)

    @staticmethod
    def clear_layout(layout: QLayout) -> None:
        """Clear a layout from all added widget

        :param layout: layout to clear
        :type layout: any Qt type layouy
        """
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                if item:
                    widget = item.widget()
                    if widget is not None:
                        widget.deleteLater()
                    else:
                        layout.removeItem(item)

    def clear_tags(self) -> None:
        """Clear displayed tags"""
        self.clear_layout(self.h_layout)

    def set_tag_list(self, tag_list: list[Tag]) -> None:
        """Defined display tag

        :param tag_list: tag list
        :type tag_list: List[Tag]
        """
        self.clear_tags()
        for tag in tag_list:
            self.add_tag(tag)
        self.h_layout.addStretch()

    def add_tag(self, tag: Tag) -> None:
        """Add tag

        :param tag: tag
        :type tag: Tag
        """
        self.h_layout.addWidget(TagLabel(tag=tag))
