# CompareDialog.py -- Pamhyr
# Copyright (C) 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 os
import logging
import tempfile

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,
)

from View.WaitingDialog import WaitingDialog

_translate = QCoreApplication.translate

logger = logging.getLogger()


class CompareScenariosWindow(PamhyrDialog):
    _pamhyr_ui = "CompareScenarios"
    _pamhyr_name = "Compare scenarios"

    def __init__(self, study=None, config=None,
                 parent=None):
        self._solvers = []
        self._scenarios = []

        name = _translate("Solver", "Compare solvers")
        super(CompareScenariosWindow, self).__init__(
            title=name,
            study=study,
            config=config,
            options=[],
            parent=parent
        )

        self.setup_solvers()
        self.setup_scenarios()
        self.setup_connections()
        self.select_last_solver()

    def setup_solvers(self):
        solvers = self._config.solvers
        solvers_name = list(
            map(
                self._format_solver_name, solvers
            )
        )

        self.combobox_add_items("comboBoxSolver1", solvers_name)
        self.combobox_add_items("comboBoxSolver2", solvers_name)

    def setup_scenarios(self):
        scenarios = self._study.scenarios.lst
        scenarios_name = list(
            map(
                lambda s: s.name, scenarios
            )
        )

        self.combobox_add_items("comboBoxScenario1", scenarios_name)
        self.combobox_add_items("comboBoxScenario2", scenarios_name)

    def setup_connections(self):
        self.find(QPushButton, "pushButton_ok").clicked.connect(self.accept)
        self.find(QPushButton, "pushButton_cancel")\
            .clicked.connect(self.reject)

    def select_last_solver(self):
        solvers = self._config.solvers
        last = self._config.last_solver_name

        solver = list(
            filter(
                lambda s: s.name == last,
                solvers
            )
        )

        if len(solver) != 0:
            self.set_combobox_text(
                "comboBoxSolver1",
                self._format_solver_name(solver[0])
            )
            self.set_combobox_text(
                "comboBoxSolver2",
                self._format_solver_name(solver[0])
            )

    def _format_solver_name(self, solver):
        return f"{solver.name} - ({solver._type})"

    @property
    def solver1(self):
        return self._solvers[0]

    @property
    def solver2(self):
        return self._solvers[1]

    @property
    def scenario1(self):
        return self._scenarios[0]

    @property
    def scenario2(self):
        return self._scenarios[1]

    def accept(self):
        for cb in ["comboBoxSolver1", "comboBoxSolver2"]:
            name = self.get_combobox_text(cb)
            name = name.rsplit(" - ", 1)[0]
            self._solvers.append(
                next(
                    filter(
                        lambda s: s.name == name,
                        self._config.solvers
                    )
                )
            )

        for cb in ["comboBoxScenario1", "comboBoxScenario2"]:
            name = self.get_combobox_text(cb)
            self._scenarios.append(
                next(
                    filter(
                        lambda s: s.name == name,
                        self._study.scenarios.lst
                    )
                )
            )

        super(CompareScenariosWindow, self).accept()
