"""Dialog for issue view"""

# standard
from pathlib import Path

# PyQGIS
from qgis.core import Qgis
from qgis.PyQt import uic
from qgis.PyQt.QtCore import Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QDialog, QWidget

# project
from oslandia.gitlab_api.group import Group, GroupRequestManager
from oslandia.gitlab_api.issue import Issues
from oslandia.gitlab_api.project import ProjectRequestManager
from oslandia.gui.wdg_view_issues import ViewIssueWidget
from oslandia.toolbelt.log_handler import PlgLogger
from oslandia.toolbelt.preferences import PlgOptionsManager


class ViewIssueDialog(QDialog):
    """QDialog to display issue from a selected project

    :param parent: dialog parent, defaults to None
    :type parent: Optional[QWidget], optional
    """

    def __init__(self, parent: QWidget | None = None):
        super().__init__(parent)
        ui_path = Path(__file__).resolve(True).parent / "dlg_view_issues.ui"
        uic.loadUi(ui_path, self)
        self.setWindowTitle(self.tr("Project issues"))
        self.plg_settings = PlgOptionsManager.get_plg_settings()
        self.log = PlgLogger().log

        # Don't display tab if only one group
        self.tabwidget_gitlab_group.setTabBarAutoHide(True)

        # make the dialog a window to allow resizing
        self.setWindowFlags(Qt.WindowType.Window)

        # Keep reference of widget for each group
        self._group_widget_dict: dict[str, ViewIssueWidget] = {}

        manager = GroupRequestManager()

        for group_id in self.plg_settings.gitlab_group_list_values:
            group = manager.get_group_from_id(group_id)
            if group:
                manager.download_avatar(group)
                self.add_gitlab_group(group)

    def add_gitlab_group(self, group: Group) -> None:
        """Add tab for a gitlab group

        :param group: group to add
        :type group: Group
        """
        widget = ViewIssueWidget(group.id, self)
        self.tabwidget_gitlab_group.addTab(
            widget, QIcon(str(group.avatar_local_filepath)), group.name
        )
        self._group_widget_dict[group.id] = widget

    def selected_project_id(self) -> int | None:
        """Get selected project id, return None if no project selected

        :return: selected project id
        :rtype: Optional[int]
        """
        widget = self.tabwidget_gitlab_group.currentWidget()
        if isinstance(widget, ViewIssueWidget):
            return widget.selected_project_id()
        return None

    def select_issue(self, issue: Issues) -> None:
        """Select issue in dialog

        :param issue: issue to select
        :type issue: Issues
        """
        project_manager = ProjectRequestManager()
        project = project_manager.get_project(project_id=issue.project_id)
        if project is None:
            self.log(
                message=f"Can't get project with ID {issue.project_id} for issue selection.",
                log_level=Qgis.MessageLevel.Warning,
                push=False,
            )
            return

        if project.group_id in self._group_widget_dict:
            self._group_widget_dict[project.group_id].select_issue(issue)
        else:
            self.log(
                message=f"Can't get group with ID {project.group_id} for issue selection.",
                log_level=Qgis.MessageLevel.Warning,
                push=False,
            )
