"""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


class MarkdownPreviewWidget(QWidget):
    def __init__(self, parent: QWidget | None = None):
        super().__init__(parent)
        ui_path = Path(__file__).resolve(True).parent / "wdg_markdown_preview.ui"
        uic.loadUi(ui_path, 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:
        if self.input_text_edit:
            """Render in the preview area."""
            md_txt = f"\n{self.input_text_edit.toPlainText()}\n"

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