"""Widget for note reply creation"""

# standard
from pathlib import Path

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

# project
from oslandia.helpdesk.discussion import (
    Discussion,
    DiscussionGraphQLRequestManager,
    Note,
)
from oslandia.toolbelt.log_handler import PlgLogger


class NoteReplyCreationWidget(QWidget):
    """QWidget to create note reply

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

    # Signal to indicate that a note reply was added
    qsig_note_reply_added = QtCore.pyqtSignal(Note)

    qsig_note_reply_canceled = QtCore.pyqtSignal()

    def __init__(self, parent: QWidget | None = None):
        super().__init__(parent)
        ui_path = Path(__file__).resolve(True).parent / "wdg_note_reply_creation.ui"
        uic.loadUi(ui_path, self)
        self.discussion = None

        self.btn_reply.setIcon(QgsApplication.getThemeIcon("mActionTiltUp.svg"))

        self.btn_reply.setEnabled(False)
        self.btn_reply.clicked.connect(self._reply)

        self.btn_cancel.clicked.connect(self.qsig_note_reply_canceled.emit)

        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_discussion(self, discussion: Discussion) -> None:
        """Define discussion used to add note

        :param discussion: discussion
        :type discussion: Discussion
        """
        self.discussion = discussion
        self.btn_reply.setEnabled(True)
        self.txt_body.set_project_id(discussion.project_id)

    def _reply(self) -> None:
        """Add comment to current discussion from displayed text"""
        if self.discussion:
            manager = DiscussionGraphQLRequestManager()
            note = manager.add_note_reply(
                issue_graphql_id=self.discussion.issue_graphql_id,
                discussion_id=self.discussion.graphql_id,
                body=self.txt_body.toPlainText(),
            )
            if note is not None:
                PlgLogger().log(
                    message=self.tr("Discussion reply 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_note_reply_added.emit(note)
