# 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.LateralContributionsAdisTS.UndoCommand import (
    SetReachCommand,
    SetBeginCommand, SetEndCommand,
    AddCommand, DelCommand,
)

from View.Tools.PamhyrTable import PamhyrTableModel

logger = logging.getLogger()

_translate = QCoreApplication.translate


class ComboBoxDelegate(QItemDelegate):
    def __init__(self, data=None, mode="reach",
                 trad=None, parent=None):
        super(ComboBoxDelegate, self).__init__(parent)

        self._data = data
        self._mode = mode
        self._trad = trad

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        self._data = data

    def createEditor(self, parent, option, index):
        self.editor = QComboBox(parent)

        if self._mode == "rk":
            if self._data is None:
                self.editor.addItems(
                    ["0"]
                )
            else:
                self.editor.addItems(
                    list(
                        map(str, self._data.reach.get_rk())
                    )
                )
        else:
            self.editor.addItems(
                [self._trad['not_associated']] +
                self._data.edges_names()
            )

        self.editor.setCurrentText(index.data(Qt.DisplayRole))
        return self.editor

    def setEditorData(self, editor, index):
        value = index.data(Qt.DisplayRole)
        self.editor.currentTextChanged.connect(self.currentItemChanged)

    def setModelData(self, editor, model, index):
        text = str(editor.currentText())
        model.setData(index, text)
        editor.close()
        editor.deleteLater()

    def updateEditorGeometry(self, editor, option, index):
        r = QRect(option.rect)
        if self.editor.windowFlags() & Qt.Popup:
            if editor.parent() is not None:
                r.setTopLeft(self.editor.parent().mapToGlobal(r.topLeft()))
        editor.setGeometry(r)

    @pyqtSlot()
    def currentItemChanged(self):
        self.commitData.emit(self.sender())


class TableModel(PamhyrTableModel):
    def __init__(self, pollutant=None, lcs_list=None, trad=None, **kwargs):
        self._trad = trad
        self._lcs_list = lcs_list
        self._pollutant = pollutant

        super(TableModel, self).__init__(trad=trad, **kwargs)
        self._setup_lst()

    def _setup_lst(self):
        if self._lcs_list is not None:
            self._lcs_pol_list = [
                lcs for lcs in self._lcs_list._lst
                if lcs.pollutant == self._pollutant
            ]

        self._lst = list(
            filter(
                lambda x: x._deleted is False,
                self._lcs_pol_list
            )
        )
        # self._tab = self._opt_data
        self._long_types = self._trad.get_dict("long_types")

    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] == "reach":
            n = self._lst[row].reach
            if n is None:
                return self._trad['not_associated']
            return next(filter(
                lambda r: r.id == n, self._data.reachs()
            )).name
        elif self._headers[column] == "begin_rk":
            return str(self._lst[row].begin_rk)
        elif self._headers[column] == "end_rk":
            return str(self._lst[row].end_rk)

        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] == "reach":
                self._undo.push(
                    SetReachCommand(
                        self._lcs_list, self._lst,
                        row,
                        self._data.reach(value).id
                    )
                )
            elif self._headers[column] == "begin_rk":
                self._undo.push(
                    SetBeginCommand(
                        self._lcs_list, self._lst, row, value
                    )
                )
            elif self._headers[column] == "end_rk":
                self._undo.push(
                    SetEndCommand(
                        self._lcs_list, 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._pollutant, self._lcs_list, self._lst, row
            )
        )

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

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

        row_by_lc = {
            id(lc): row for row, lc in enumerate(self._lcs_list._lst)
        }
        global_rows = [
            row_by_lc[id(self._lst[row])]
            for row in rows
            if 0 <= row < len(self._lst)
        ]
        self._undo.push(
            DelCommand(
                self._lcs_list, global_rows
            )
        )

        self._setup_lst()
        self.endRemoveRows()
        self.layoutChanged.emit()

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

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