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

from functools import reduce
from tools import trace, timer

from PyQt5.QtCore import (
    Qt, QVariant,
)

from PyQt5.QtGui import (
    QColor, QBrush,
)

from View.Tools.PamhyrList import PamhyrListModel
from View.GeoTIFF.UndoCommand import (
    AddCommand, DelCommand
)

logger = logging.getLogger()


class ListModel(PamhyrListModel):
    def get_true_data_row(self, row):
        el = self._data.get(row)

        return next(
            map(
                lambda e: e[0],
                filter(
                    lambda e: e[1] == el,
                    enumerate(self._data._lst)
                )
            ), 0
        )

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

        file = self._data.files[row]

        if role == Qt.ForegroundRole:
            color = Qt.gray

            if file.is_enabled():
                color = QColor("black")
            else:
                color = QColor("grey")

            return QBrush(color)

        if role == Qt.ItemDataRole.DisplayRole:
            text = f"{file.name}: '{file.description}'"

            if not file.is_enabled():
                text += " (disabled)"

            return text

        return QVariant()

    def add(self, row):
        row = self.get_true_data_row(row)

        self._undo.push(
            AddCommand(
                self._data, row
            )
        )
        self.update()

    def delete(self, row):
        self._undo.push(
            DelCommand(
                self._data, self._data.files[row]
            )
        )
        self.update()
