"""Widget for markdown preview for input text edit"""

# standard
from pathlib import Path

# PyQGIS
from qgis.core import QgsApplication
from qgis.PyQt import uic
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QTextEdit, QWidget

from oslandia.gui.stylesheet import WidgetStyleSheet

# plugin
from oslandia.helpdesk.markdown import strip_markdown_html_comments


class MarkdownPreviewWidget(WidgetStyleSheet):
    def __init__(self, parent: QWidget | None = None):
        super().__init__(parent)
        uic.loadUi(Path(__file__).parent / f"{Path(__file__).stem}.ui", self)

        # connect preview button
        self.btn_preview.setIcon(
            QIcon(QgsApplication.iconPath("mActionShowAllLayersGray.svg"))
        )
        self.btn_preview.clicked.connect(self.generate_preview)
        self.txt_preview.setStyleSheet("background-color: #DCDCDC;")

        self.input_text_edit = None

    def set_input_text_edit(self, lne: QTextEdit) -> None:
        """Define input text edit used for preview

        :param lne: text edit for input preview
        :type lne: QTextEdit
        """
        if self.input_text_edit:
            self.input_text_edit.textChanged.disconnect(self.auto_preview)
        self.input_text_edit = lne
        self.input_text_edit.textChanged.connect(self.auto_preview)

    def auto_preview(self) -> None:
        """To be connected to input widgets. Triggers the preview if the related
        checkbox is checked.
        """
        if self.chb_auto_preview.isChecked():
            self.generate_preview()

    def generate_preview(self) -> None:
        """Convert the text from edit widget to markdown and display in preview widget."""
        if self.input_text_edit:
            content = (
                strip_markdown_html_comments(self.input_text_edit.toPlainText()) or ""
            )
            md_txt = f"\n{content}\n"

            # show it
            self.txt_preview.clear()
            self.txt_preview.setMarkdown(md_txt)
