# Table.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
import traceback

from tools import logger_exception

from View.Scenarios.GraphWidget import GraphWidget
from View.Scenarios.UndoCommand import *
from View.Tools.PamhyrTable import PamhyrTableModel

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

from PyQt5.QtWidgets import (
    QTableView, QItemDelegate, QComboBox, QLineEdit, QHBoxLayout, QSlider,
    QPushButton, QCheckBox, QStyledItemDelegate, QStyleOptionButton, QStyle,
    QApplication,
)

logger = logging.getLogger()


class ScenariosTableModel(PamhyrTableModel):
    def _setup_lst(self):
        self._lst = list(
            filter(
                lambda x: not x.is_deleted(),
                self._data.scenarios.lst
            )
        )

    def rowCount(self, parent=QModelIndex()):
        self._setup_lst()

        return len(self._lst)

    def data(self, index, role):
        if role != Qt.ItemDataRole.DisplayRole:
            return QVariant()

        value = self._lst[index.row()]

        if self._headers[index.column()] == "parent":
            parent = value["parent"]
            if parent is None:
                return ""

            return parent.name

        return value[self._headers[index.column()]]

    @pyqtSlot()
    def setData(self, index, value, role=Qt.EditRole):
        if not index.isValid():
            return False

        if role == Qt.EditRole:
            if self.is_same_data(index, value):
                return False

            try:
                self._undo.push(
                    SetCommand(
                        self._lst[index.row()],
                        self._headers[index.column()],
                        value
                    )
                )
            except Exception as e:
                logger_exception(e)

                self.layoutChanged.emit()
                return True

            self.dataChanged.emit(index, index)

    def update(self):
        self._lst = self._data.scenarios.lst
        self.layoutChanged.emit()
