# 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 Model.Network.Node import Node
from Model.Network.Edge import Edge
from Model.Network.Graph import Graph
from View.Network.GraphWidget import GraphWidget
from View.Network.UndoCommand import *
from View.Tools.PamhyrTable import PamhyrTableModel

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

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

logger = logging.getLogger()


class ComboBoxDelegate(QItemDelegate):
    def __init__(self, graph=None, parent=None):
        super(ComboBoxDelegate, self).__init__(parent)
        self.graph = graph

    def createEditor(self, parent, option, index):
        self.editor = QComboBox(parent)
        self.editor.addItems(self.graph.nodes_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 NodeTableModel(PamhyrTableModel):
    def _setup_lst(self):
        self._lst = self._data.nodes()

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

        if self._headers[index.column()] == "type":
            node = self._lst[index.row()]
            ret = "internal"

            if not self._data.is_enable_node(node):
                ret = "disable"
            elif self._data.is_upstream_node(node):
                ret = "upstream"
            elif self._data.is_downstream_node(node):
                ret = "downstream"

            return ret

        if self._headers[index.column()] == "name":
            return self._trad.node_name(self._lst[index.row()])

        return self._lst[index.row()][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.info(e)
                logger.debug(traceback.format_exc())

                self.dataChanged.emit(index, index, [Qt.DisplayRole])
                self.layoutChanged.emit()
                return True

            self.dataChanged.emit(index, index)

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


class EdgeTableModel(PamhyrTableModel):
    def _setup_lst(self):
        self._lst = self._data.edges()

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

        if (self._headers[index.column()] == "node1" or
                self._headers[index.column()] == "node2"):
            return self._trad.node_name(
                self._lst[index.row()][self._headers[index.column()]]
            )

        if self._headers[index.column()] == "name":
            return self._trad.edge_name(self._lst[index.row()])

        return self._lst[index.row()][self._headers[index.column()]]

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

        if role != Qt.EditRole:
            return QVariant()

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

        try:
            if (self._headers[index.column()] == "node1" or
                    self._headers[index.column()] == "node2"):
                node = self._data.node(value)
                self._undo.push(
                    SetNodeCommand(
                        self._data,
                        self._lst[index.row()],
                        self._headers[index.column()],
                        node
                    )
                )
            else:
                self._undo.push(
                    SetCommand(
                        self._lst[index.row()],
                        self._headers[index.column()],
                        value
                    )
                )
        except Exception as e:
            logger.info(e)
            logger.debug(traceback.format_exc())

            self.dataChanged.emit(index, index, [Qt.DisplayRole])
            self.layoutChanged.emit()
            return True

        self.dataChanged.emit(index, index)

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