# standard
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

# PyQGIS
from qgis.core import Qgis
from qgis.PyQt import uic
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtWidgets import QWidget

from oslandia.gui.stylesheet import WidgetStyleSheet

# project
from oslandia.newsfeed.rss_reader import RssReader
from oslandia.toolbelt import PlgLogger, PlgOptionsManager


if TYPE_CHECKING:
    from oslandia.toolbelt.preferences import PlgSettingsStructure


class WdgSettingsRss(WidgetStyleSheet):
    """Widget containing Newsfeed options."""

    def __init__(self, parent: QWidget | None = None) -> None:
        """Widget for the RSS section in the settings dialog.

        :param parent: parent widget, defaults to None
        :type parent: QObject, optional
        """
        super().__init__(parent)
        uic.loadUi(Path(__file__).parent / f"{Path(__file__).stem}.ui", self)

        self.log = PlgLogger().log
        self.plg_settings = PlgOptionsManager()
        self.rss_reader = RssReader()
        self.initGui()

    def initGui(self) -> None:  # noqa: N802
        """Set up RSS-related UI elements."""
        self.btn_reset_rss_history.pressed.connect(self.on_reset_read_history)
        self.load_user_filters()

    def load_settings(self) -> None:
        """Load RSS options from QgsSettings into the widget."""
        plg_settings: PlgSettingsStructure = self.plg_settings.get_plg_settings()

        self.lbl_rss_url.setText(
            f'<a href="{plg_settings.rss_source}">{plg_settings.rss_source}</a>'
        )
        self.chb_notification_rss_new_content.setChecked(
            plg_settings.rss_notify_push_info
        )
        self.chb_view_only_rss_unread.setChecked(plg_settings.rss_view_only_unread)
        self.sbx_rss_poll_frequency.setValue(plg_settings.rss_poll_frequency_hours)
        self.sbx_notif_duration.setValue(plg_settings.rss_notify_push_duration)

    def save_settings(self) -> None:
        """Persist RSS options from the widget into QgsSettings."""
        plg_settings: PlgSettingsStructure = self.plg_settings.get_plg_settings()
        plg_settings.rss_notify_push_info = (
            self.chb_notification_rss_new_content.isChecked()
        )
        plg_settings.rss_notify_push_duration = self.sbx_notif_duration.value()
        plg_settings.rss_poll_frequency_hours = self.sbx_rss_poll_frequency.value()
        user_filters = self.cbx_rss_user_filters.checkedItems()
        plg_settings.rss_category_filters = ",".join(user_filters)
        plg_settings.rss_view_only_unread = self.chb_view_only_rss_unread.isChecked()

        self.plg_settings.save_from_object(plg_settings)

    def on_reset_read_history(self) -> None:
        """Reset 'latest_content_guid' and 'rss_read_items' to an empty string."""
        plg_settings: PlgSettingsStructure = self.plg_settings.get_plg_settings()
        plg_settings.rss_latest_content_guid = plg_settings.rss_read_items = ""
        self.plg_settings.save_from_object(plg_settings)

        self.log(
            message=self.tr("Read history has been reset."),
            log_level=Qgis.MessageLevel.Success,
            duration=5,
            push=True,
        )

    def load_user_filters(self) -> None:
        """Load the last news tags in the filters list"""
        rss = self.rss_reader.read_rss(no_filter=True)
        self.cbx_rss_user_filters.clear()
        list_available_filters = []
        for item in rss:
            for cat in item.categories:
                if cat not in list_available_filters:
                    list_available_filters.append(cat)
        for cat in list_available_filters:
            self.cbx_rss_user_filters.addItem(cat)

        # And complete with actual filters
        plg_settings: PlgSettingsStructure = self.plg_settings.get_plg_settings()
        user_filters: list[str] = [
            filter_cat.strip()
            for filter_cat in plg_settings.rss_category_filters.split(",")
        ]
        for f in user_filters:
            if f not in list_available_filters:
                # Add it and check it
                self.cbx_rss_user_filters.addItemWithCheckState(
                    f, state=Qt.CheckState.Checked
                )
            else:
                # Check it
                self.cbx_rss_user_filters.setItemCheckState(
                    self.cbx_rss_user_filters.findText(f), state=Qt.CheckState.Checked
                )

        self.cbx_rss_user_filters.model().sort(0)
