# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copied directly from the AequilibraE plugin
import os
import tempfile

from qgis.PyQt import QtWidgets, uic
from qgis.PyQt.Qsci import QsciLexerYAML
from qgis.PyQt.QtGui import QFont

FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), "forms/ui_parameters.ui"))


class LogDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, iface, parent=None):
        super(LogDialog, self).__init__(parent)

        temp_folder = tempfile.gettempdir()

        self.logfile = os.path.join(temp_folder, "polarisnetwork.log")

        self.iface = iface
        self.setupUi(self)

        self.default_values = None
        self.parameter_values = None
        self.current_data = None
        self.error = False
        # Configures the text editor
        font = QFont()
        font.setFamily("Courier")
        font.setFixedPitch(True)
        font.setPointSize(12)
        lexer = QsciLexerYAML()  # The lexer doesn't really matter
        lexer.setDefaultFont(font)
        self.text_box.setLexer(lexer)
        self.text_box.setFolding(self.text_box.PlainFoldStyle)

        # Load the data
        self.load_data()

        # Connect all buttons
        self.but_close.clicked.connect(self.exit_procedure)
        self.but_clear.clicked.connect(self.clear_log)

    # Load the current parameters onto the GUI
    def load_data(self):
        if not os.path.isfile(self.logfile):
            return
        with open(self.logfile, "r") as log:
            logdata = log.readlines()
        self.text_box.setText("".join(logdata))

    def clear_log(self):
        with open(self.logfile, "w") as _:
            pass
        self.close()

    def exit_procedure(self):
        self.close()
