# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
import numpy as np
from qgis.PyQt import QtCore, QtWidgets, uic

Qt = QtCore.Qt


# This class was adapted from https://www.mail-archive.com/pyqt@riverbankcomputing.com/msg17575.html
# Provided by David Douard

# adaptations for headers come from: http://stackoverflow.com/questions/14135543/how-to-set-the-qtableview-header-name-in-pyqt4


class NumpyModel(QtCore.QAbstractTableModel):
    def __init__(self, matrix, indices, separator, decimals, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self._array = matrix
        self.separator = "," if separator else ""
        self.header_fmt = "{:" + self.separator + "}"
        self.data_fmt = "{:" + self.separator + "." + str(decimals) + "f}"

        self.row_headers_data = [self.header_fmt.format(x) for x in indices]
        self.header_data = [self.header_fmt.format(x) for x in indices]

    def rowCount(self, parent=None):
        return self._array.shape[0]

    def columnCount(self, parent=None):
        return self._array.shape[1]

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or role != Qt.DisplayRole:
            return None

        row, col = index.row(), index.column()
        if (
            (np.issubdtype(self._array.dtype, np.integer) and (self._array == self.empties))
            or np.isnan(self._array[row, col])
            or np.isinf(self._array[row, col])
        ):
            return ""
        return self.data_fmt.format(self._array[row, col])

    def headerData(self, col, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return self.header_data[col]
            return self.row_headers_data[col]

        return QtCore.QAbstractTableModel.headerData(self, col, orientation, role)
