# 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 logging

from tools import trace, timer

from View.Tools.PamhyrWindow import PamhyrWindow

from PyQt5.QtGui import (
    QKeySequence,
)

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

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

from View.SolverParameters.UndoCommand import *
from View.SolverParameters.Table import TableModel
from View.SolverParameters.translate import ParamTranslate

from Solver.Solvers import solver_long_name, solver_type_list

_translate = QCoreApplication.translate

logger = logging.getLogger()


class SolverParametersWindow(PamhyrWindow):
    _pamhyr_ui = "SolverParameters"
    _pamhyr_name = "Solver parameters"

    def __init__(self, study=None, config=None, parent=None):
        trad = ParamTranslate()
        name = trad[self._pamhyr_name] + " - " + study.name
        super(SolverParametersWindow, self).__init__(
            title=name,
            study=study,
            config=config,
            options=['copy'],
            trad=trad,
            parent=parent
        )

        self._params = self._study.river.parameters

        self.setup_sc()
        self.setup_table()

    def setup_sc(self):
        self._undo_stack = {}

        for st in solver_type_list:
            self._undo_stack[st] = QUndoStack()

        self._undo_sc = QShortcut(QKeySequence.Undo, self)
        self._redo_sc = QShortcut(QKeySequence.Redo, self)
        self._undo_sc.activated.connect(self._undo)
        self._redo_sc.activated.connect(self._redo)

    def setup_table(self):
        self._table = {}
        self._tab_widget = self.find(QTabWidget, f"tabWidget")

        if self._study.is_editable():
            editable_headers = ["value"]
        else:
            editable_headers = []

        for st in solver_type_list:
            # Create widgets
            widget = QWidget()
            grid = QGridLayout()
            table = QTableView()

            widget.setObjectName(f"tab_{st}")
            table.setObjectName(f"tableView_{st}")

            # Create table model
            self._table[st] = TableModel(
                table_view=table,
                data=self._study.river,
                opt_data=st,
                table_headers=self._trad.get_dict("table_headers"),
                editable_headers=editable_headers,
                trad=self._trad,
                undo=self._undo_stack[st],
            )

            table.setModel(self._table[st])
            table.setSelectionBehavior(QAbstractItemView.SelectRows)
            table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            table.setAlternatingRowColors(True)

            # Add table to tab
            grid.addWidget(table, 0, 0)
            widget.setLayout(grid)
            table.setParent(widget)

            # Create tab
            self._tab_widget.addTab(widget, f"{solver_long_name[st]}")

    def current_tab(self):
        return self.find(QTabWidget, "tabWidget")\
                   .currentWidget()\
                   .objectName()\
                   .replace("tab_", "")

    def _undo(self):
        tab = self.current_tab()
        self._table[tab].undo()
        self._set_current_reach()

    def _redo(self):
        tab = self.current_tab()
        self._table[tab].redo()
        self._set_current_reach()

    def _copy(self):
        logger.info("TODO: copy")

    def _paste(self):
        logger.info("TODO: paste")
