# PyQGIS
from qgis.PyQt import QtCore
from qgis.PyQt.QtGui import QContextMenuEvent, QIcon
from qgis.PyQt.QtWidgets import QMenu

# plugin
from oslandia.__about__ import DIR_PLUGIN_ROOT
from oslandia.gui.commons.lbl_tag import Tag, TagLabel
from oslandia.toolbelt.preferences import PlgOptionsManager


class FilterTagLabel(TagLabel):
    """Custom widget for RSS tags (categories)"""

    qsig_tag_filters_changed = QtCore.pyqtSignal(str, str)

    def __init__(self) -> None:
        """Initialize the FilterTagLabel widget."""
        super().__init__(tag=Tag(name=""))

    def contextMenuEvent(self, event: QContextMenuEvent) -> None:  # noqa: N802
        """ContextMenu event : add or remove menu for tags"""
        menu = QMenu(self)
        menu.setStyleSheet("background-color: #eee; color: #000")
        plg_settings = PlgOptionsManager.get_plg_settings()
        existing_filters = []
        if plg_settings.rss_category_filters.strip() != "":
            existing_filters = [
                x.strip().lower() for x in plg_settings.rss_category_filters.split(",")
            ]

        action_add = menu.addAction(self.tr("Add to filters"))
        action_add.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources/images/add_to_filters.svg"))
        )
        action_add.triggered.connect(
            lambda state, action="add": self.add_or_remove_filters(action)
        )
        action_add.setVisible(True)
        if self.text().lower() in existing_filters:
            action_add.setVisible(False)

        action_remove = menu.addAction(self.tr("Remove from filters"))
        action_remove.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources/images/remove_from_filters.svg"))
        )
        action_remove.triggered.connect(
            lambda state, action="remove": self.add_or_remove_filters(action)
        )
        action_remove.setVisible(True)
        if self.text().lower() not in existing_filters:
            action_remove.setVisible(False)

        menu.exec(event.globalPos())

    def add_or_remove_filters(self, action: str = "add") -> None:
        """Emit an add or remove signal tag to change filters in settings.

        :param add: tells if it's add or remove
        :type add: string
        """
        self.qsig_tag_filters_changed.emit(action, self.text())
