# Copyright (c) 2021 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.

from typing import Optional
import re

from PyQt6.QtCore import QObject, pyqtSlot

from UM.i18n import i18nCatalog
from UM.Resources import Resources

catalog = i18nCatalog("cura")

#
# This manager provides means to load texts to QML.
#
class TextManager(QObject):

    def __init__(self, parent: Optional["QObject"] = None) -> None:
        super().__init__(parent)

        self._change_log_text = ""

    @pyqtSlot(result = str)
    def getChangeLogText(self) -> str:
        if not self._change_log_text:
            self._change_log_text = self._loadChangeLogText()
        return self._change_log_text

    def _loadChangeLogText(self) -> str:
        # Load change log texts and organize them with a dict
        try:
            file_path = Resources.getPath(Resources.Texts, "change_log.txt")
        except FileNotFoundError as e:
            # I have no idea how / when this happens, but we're getting crash reports about it.
            return catalog.i18nc("@text:window", "The release notes could not be opened.") + "<br>" + str(e)
        content = ""
        try:
            # modified by bigrep
            with open(file_path, "r", encoding = "utf-8") as f:
                lines = f.readlines()
            for line in lines:
                l = line.rstrip()
                if l.startswith('- '):
                    # regular line
                    content += f"{l}<br>"
                elif l=="":
                    content += "<br>"
                else:
                    # heading
                    content += f"<h2>{l}</h2>"

            return content

        except EnvironmentError as e:
            return catalog.i18nc("@text:window", "The release notes could not be opened.") + "<br>" + str(e)
