# Table.py -- Pamhyr
# Copyright (C) 2023-2025  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.WeatherParameters.UndoCommand import (
    SetCommand, AddCommand, DelCommand,
    SetEdgeCommand, SetBeginCommand, SetEndCommand,
)

logger = logging.getLogger()

_translate = QCoreApplication.translate


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

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

    @property
    def weather_param_lst(self):
        return self._weather_param_lst

    @weather_param_lst.setter
    def weather_param_lst(self, weather_param_lst):
        self._weather_param_lst = weather_param_lst
        # self.modified()

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

        if self._mode == "rk":
            wp = index.model().get(index.row())
            if wp is None and self._weather_param_lst is not None:
                wp = self._weather_param_lst.get(index.row())
            if wp is None or wp.reach is None:
                self.editor.addItems(
                    ["-"]
                )
            else:
                self.editor.addItems(
                    list(
                        map(
                            lambda p: p.display_name(),
                            wp.reach.reach.profiles
                        )
                    )
                )
        else:
            self.editor.addItems(
                [self._trad['not_associated']] +
                self._data.edges_names()
            )

        self.editor.setCurrentText(str(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())

        if self._mode == "rk":
            value = None
            wp = index.model().get(index.row())
            if wp is None and self._weather_param_lst is not None:
                wp = self._weather_param_lst.get(index.row())
            if wp is not None and wp.reach is not None:
                profiles = list(
                    filter(
                        lambda p: p.display_name() == text,
                        wp.reach.reach.profiles
                    )
                )
                value = profiles[0].pamhyr_id if len(profiles) > 0 else None
        else:
            value = text

        model.setData(index, value)
        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 WeatherParametersTableModel(PamhyrTableModel):
    def __init__(self, river=None, data=None, **kwargs):
        self._river = river
        self._data = data
        self._type = "ND"

        super(WeatherParametersTableModel, self).__init__(data=data, **kwargs)

    def _setup_lst(self):
        if self._type == "ND" or self._data is None:
            self._lst = []
            return
        self._lst = self._data.lst
        self._lst = list(filter(lambda wp: wp.type == self._type, self._lst))

    def update_tab_spec(self, type="ND", enabled=True):
        if enabled:
            self._type = type
            self._setup_lst()
            self.layoutChanged.emit()
        else:
            self._type = "ND"
            self._lst = []
            self.layoutChanged.emit()

    def get(self, row):
        if row < 0 or row >= len(self._lst):
            return None
        return self._lst[row]

    def _global_row(self, row):
        wp = self.get(row)
        if wp is None:
            return None
        return self._data.index(wp)

    def _global_insert_row(self, row):
        if row < len(self._lst):
            return self._global_row(row)
        return len(self._data)

    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":
            reach = self._lst[row].reach
            if reach is None:
                return self._trad['not_associated']
            return reach.name
        elif self._headers[column] == "start_rk":
            section = self._lst[row].begin_section
            if section is None:
                return self._trad['not_associated']
            return section.display_name()
        elif self._headers[column] == "end_rk":
            section = self._lst[row].end_section
            if section is None:
                return self._trad['not_associated']
            return section.display_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:
            global_row = self._global_row(row)
            if global_row is None:
                return False

            if self._headers[column] == "start_rk":
                _edge = self._data.get(global_row).reach
                _begin_rk = next(
                    p for p in _edge.reach.profiles
                    if p.pamhyr_id == value
                )
                self._undo.push(
                    SetBeginCommand(
                        self._data, global_row, _begin_rk
                    )
                )
            elif self._headers[column] == "end_rk":
                _edge = self._data.get(global_row).reach
                _end_rk = next(
                    p for p in _edge.reach.profiles
                    if p.pamhyr_id == value
                )
                self._undo.push(
                    SetEndCommand(
                        self._data, global_row, _end_rk
                    )
                )
            elif self._headers[column] == "reach":
                self._undo.push(
                    SetEdgeCommand(
                        self._data, global_row, self._river.edge(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)

        self._undo.push(
            AddCommand(
                self._data, self._type, self._lst,
                self._global_insert_row(row)
            )
        )

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

    def delete(self, rows, parent=QModelIndex()):
        self.beginRemoveRows(parent, rows[0], rows[-1])
        data_rows = {
            id(wp): i for i, wp in enumerate(self._data.lst)
        }
        self._undo.push(
            DelCommand(
                wps=self._data,
                rows=[
                    data_rows[id(self._lst[row])]
                    for row in rows
                    if 0 <= row < len(self._lst)
                ]
            )
        )

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