"""Widget for note creation"""

# standard
from pathlib import Path

# PyQGIS
from qgis.core import Qgis
from qgis.PyQt import QtCore, uic
from qgis.PyQt.QtGui import QPalette
from qgis.PyQt.QtWidgets import QWidget

from oslandia.gui.stylesheet import WidgetStyleSheet
from oslandia.helpdesk.discussion import (
    Discussion,
    DiscussionGraphQLRequestManager,
)

# project
from oslandia.helpdesk.issue import Issues
from oslandia.toolbelt.log_handler import PlgLogger


class NoteCreationWidget(WidgetStyleSheet):
    """QWidget to create note

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

    # Signal to indicate that a note was added
    qsig_discussion_added = QtCore.pyqtSignal(Discussion)

    def __init__(self, parent: QWidget | None = None):
        super().__init__(parent)
        ui_path = Path(__file__).resolve(True).parent / "wdg_note_creation.ui"
        uic.loadUi(ui_path, self)
        self.issue = None
        self.btn_comment.setEnabled(False)
        self.btn_comment.clicked.connect(self._comment)

        palette = self.txt_body.palette()
        normal = palette.color(QPalette.ColorRole.Base).name()

        self.txt_body.setStyleSheet(
            f"""
            QTextEdit {{
                border-radius: 15px;
                border: 2px solid lightblue;
                padding: 10px;
                background-color: {normal};
            }}
        """
        )

    def set_issue(self, issue: Issues) -> None:
        """Define issue used to add note

        :param issue: issue
        :type issue: Issues
        """
        self.issue = issue
        self.btn_comment.setEnabled(True)
        self.txt_body.set_project_id(issue.project_id)

    def _comment(self) -> None:
        """Add comment to current issue from displayed text"""
        if self.issue:
            manager = DiscussionGraphQLRequestManager()
            discussion: Discussion | None = manager.create_issue_note(
                self.issue.id, self.txt_body.toPlainText()
            )
            if discussion is not None:
                PlgLogger().log(
                    message=self.tr("Discussion added."),
                    log_level=Qgis.MessageLevel.Success,
                    push=True,
                    duration=5,
                    parent_location=self,
                    nb_parent_max_for_message_bar=10,
                )
                self.txt_body.clear()
                self.qsig_discussion_added.emit(discussion)
