# 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 trace, timer

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

from View.Tools.PamhyrTable import PamhyrTableModel

from View.Pollutants.UndoCommand import (
    SetNameCommand,
    SetEnabledCommand, AddCommand, DelCommand,
)

logger = logging.getLogger()

_translate = QCoreApplication.translate


class TableModel(PamhyrTableModel):
    def _setup_lst(self):
        self._lst = list(
            filter(
                lambda dif: dif._deleted is False,
                self._data._Pollutants._lst
            )
        )

    def rowCount(self, parent):
        return len(self._lst)

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

        row = index.row()
        column = index.column()

        if self._headers[column] == "name":
            return self._lst[row].name

        return QVariant()

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

        if self.is_same_data(index, value):
            return False

        row = index.row()
        column = index.column()

        try:
            if self._headers[column] == "name":
                self._undo.push(
                    SetNameCommand(
                        self._lst, row, value
                    )
                )
        except Exception as e:
            logger.info(e)
            logger.debug(traceback.format_exc())

        self.dataChanged.emit(index, index)
        return True

    def add(self, row, parent=QModelIndex()):
        self.beginInsertRows(parent, row, row - 1)

        self._undo.push(
            AddCommand(
                self._data._Pollutants, row, self._data.ic_adists
            )
        )

        self._setup_lst()
        self.endInsertRows()
        self.layoutChanged.emit()

    def delete(self, rows, parent=QModelIndex()):
        self.beginRemoveRows(parent, rows[0], rows[-1])

        data_rows = {
            id(pol): i for i, pol in enumerate(self._data._Pollutants._lst)
        }
        self._undo.push(
            DelCommand(
                self._data._Pollutants,
                [data_rows[id(self._lst[row])] for row in rows
                    if 0 <= row < len(self._lst)],
                self._data.ic_adists
            )
        )
        self._setup_lst()
        self.endRemoveRows()
        self.layoutChanged.emit()

    def enabled(self, row, enabled, parent=QModelIndex()):
        self._undo.push(
            SetEnabledCommand(
                self._lst, row, enabled
            )
        )
        self.layoutChanged.emit()

    def undo(self):
        self._undo.undo()
        self.layoutChanged.emit()

    def redo(self):
        self._undo.redo()
        self.layoutChanged.emit()
