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

from PyQt5.QtGui import (
    QKeySequence, QColor
)
from PyQt5.QtCore import (
    Qt, QAbstractTableModel, QModelIndex,
    QVariant, pyqtSlot, QCoreApplication,
)
from PyQt5.QtWidgets import (
    QMessageBox, QUndoCommand, QUndoStack,
    QStyledItemDelegate, QLineEdit, QAbstractItemView,
    QComboBox,
)

from View.Tools.PamhyrTable import PamhyrTableModel
from View.Results.translate import *

logger = logging.getLogger()

_translate = QCoreApplication.translate


class TableModel(PamhyrTableModel):
    def _setup_lst(self):
        _river = self._data.river
        self._timestamp = min(list(self._data.get("timestamps")))
        if self._opt_data == "reach":
            self._lst = _river.reachs
        elif self._opt_data == "profile":
            self._lst = _river.reach(0).profiles
        elif self._opt_data == "raw_data":
            self._lst = _river.reach(0).profiles
        elif self._opt_data == "pollutants":
            tmp_list = self._data.pollutants_list.copy()
            tmp_list.remove("total_sediment")
            self._lst = tmp_list

    def __init__(self, type_pol, **kwargs):
        self._type_pol = type_pol
        super(TableModel, self).__init__(**kwargs)

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

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

        if self._opt_data == "reach":
            if self._headers[column] == "name":
                v = self._lst[row].name
                return str(v)
        elif self._opt_data == "pollutants":
            if self._headers[column] == "name":
                v = self._lst[row]
                return str(v)
        elif self._opt_data == "profile":
            if self._headers[column] == "name":
                v = self._lst[row].name
                return str(v)
            elif self._headers[column] == "rk":
                v = self._lst[row].rk
                return f"{v:.4f}"
        elif self._opt_data == "raw_data":
            p = self._lst[row]
            if self._headers[column] == "name":
                if p.name == "":
                    return f"{p.rk:.4f}"
                return f"{p.name}"
            tmp_list = self._data.pollutants_list.copy()
            tmp_list.remove("total_sediment")
            tmp_list2 = self._data.pollutants_list.copy()
            for pol in tmp_list:
                pol_index = tmp_list2.index(pol)
                header_name = pol + " Concentration"
                if self._headers[column] == header_name:
                    v = self._lst[row].get_ts_key(
                        self._timestamp, "pols")[pol_index][0]
                    return f"{v:.4f}"
                if self._headers[column] == pol + " Mass":
                    if self._type_pol[pol_index] == 7:
                        m1 = self._lst[row].get_ts_key(
                            self._timestamp, "pols")[pol_index][1]
                        m2 = self._lst[row].get_ts_key(
                            self._timestamp, "pols")[pol_index][2]
                        m3 = self._lst[row].get_ts_key(
                            self._timestamp, "pols")[pol_index][3]
                        v = m1 + m2 + m3
                        return f"{v:.4f}"
                    else:
                        return ""

        return QVariant()

    def update(self, reach):
        _river = self._data.river

        if self._opt_data == "reach":
            self._lst = _river.reachs
        elif self._opt_data == "profile" or self._opt_data == "raw_data":
            self._lst = _river.reach(reach).profiles

        self.layoutChanged.emit()

    @property
    def timestamp(self):
        return self._timestamp

    def set_timestamp(self, timestamp):
        self._timestamp = timestamp
        self.layoutChanged.emit()
