# 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
from tempfile import gettempdir

from qgis.PyQt import QtWidgets, uic

from .get_output_file_name import GetOutputFileName

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


class ReportDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, iface, reporting):
        QtWidgets.QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)
        self.path = gettempdir()
        self.reporting = reporting
        self.output_name = None
        for t in reporting:
            self.all_data.append(t)

        self.but_save_log.clicked.connect(self.save_log)
        self.but_close.clicked.connect(self.exit_procedure)

    def save_log(self):
        if self.output_name is None:
            self.__get_name()

        with open(self.output_name, "w") as outp:
            for t in self.reporting:
                outp.write(f"{t}\n")
        self.exit_procedure()

    def __get_name(self):
        file_types = ["Text files(*.txt)"]
        self.output_name, _ = GetOutputFileName(self, "Save procedure log", file_types, ".txt", self.path)

    def exit_procedure(self):
        self.close()
