# Window.py -- Pamhyr
# Copyright (C) 2023-2026  INRAE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-

import tempfile
import os

from queue import Queue
from tools import trace, timer, logger_exception

from View.Tools.PamhyrWindow import PamhyrDialog, PamhyrWindow

from PyQt5.QtGui import (
    QKeySequence,
)

from PyQt5.QtCore import (
    Qt, QVariant, QAbstractTableModel,
    QCoreApplication, QModelIndex, pyqtSlot,
    QRect, QTimer, QProcess,
)

from PyQt5.QtWidgets import (
    QDialogButtonBox, QPushButton, QLineEdit,
    QFileDialog, QTableView, QAbstractItemView,
    QUndoStack, QShortcut, QAction, QItemDelegate,
    QComboBox, QVBoxLayout, QHeaderView, QTabWidget,
    QTextEdit,
)

_translate = QCoreApplication.translate


class SolverLogFileWindow(PamhyrWindow):
    _pamhyr_ui = "SolverLogFile"
    _pamhyr_name = "Solver logs"

    def __init__(self, file_name=None,
                 study=None, config=None,
                 solver=None, parent=None):
        self._solver = solver
        self._file_name = file_name

        name = _translate("Solver", "Solver logs")
        super(SolverLogFileWindow, self).__init__(
            title=name,
            study=study,
            config=config,
            options=[],
            parent=parent
        )

        self.setup_action()
        self.setup_connections()
        self.setup_text()

    def setup_action(self):
        self.find(QAction, "action_revert").setEnabled(True)
        if self._config.editor != "":
            self.find(QAction, "action_open_in_editor").setEnabled(True)
        else:
            self.find(QAction, "action_open_in_editor").setEnabled(False)

    def setup_connections(self):
        self.find(QAction, "action_revert").triggered.connect(self.revert)
        self.find(QAction, "action_open_in_editor").triggered.connect(
            self.open_on_editor)

    def setup_text(self):
        try:
            with open(self._file_name, "r") as f:
                for line in f:
                    line = line.rstrip()
                    self.find(QTextEdit, "textEdit").append(line)
        except Exception as e:
            logger_exception(e)

    def revert(self):
        self.find(QTextEdit, "textEdit").clear()
        self.setup_text()

    def open_on_editor(self):
        try:
            p = QProcess(self)

            cmd = self._config.editor
            cmd = cmd.replace("@file", self._file_name)

            cmd = cmd.split()
            exe = cmd[0]
            args = cmd[1:]

            p.start(
                exe, args,
            )
        except Exception as e:
            logger_exception(e)
