# Table.py -- Pamhyr
# Copyright (C) 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

from functools import reduce
from tools import trace, timer, _timers, _calls, reset_timers

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 Modules import Modules
from View.Tools.PamhyrTable import PamhyrTableModel

logger = logging.getLogger()


class TableModel(PamhyrTableModel):
    def _setup_lst(self):
        self._lst = sorted(
            map(
                lambda f: (
                    f"{f.__module__}.{f.__qualname__}",
                    _timers[f],
                    _calls[f]
                ),
                _timers
            ),
            key=lambda f: f[1],
            reverse=True
        )

    def update_lst(self):
        self._setup_lst()
        self.layoutChanged.emit()

    def reset_timers(self):
        reset_timers()
        self.update_lst()

    def data(self, index, role):
        row = index.row()
        column = index.column()

        if role == Qt.DisplayRole:
            if self._headers[column] == "name":
                return self._lst[row][0]
            elif self._headers[column] == "time":
                return self._lst[row][1]
            elif self._headers[column] == "calls":
                return self._lst[row][2]

        return QVariant()

    def to_csv(self):
        data = "\n".join(map(lambda x: f"{x[0]},{x[1]},{x[2]}", self._lst))
        return f"""name,time,calls\n{data}\n"""
