# Table.py -- Pamhyr
# Copyright (C) 2023  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 time
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 Model.Geometry import Reach
from Model.Geometry.ProfileXYZ import ProfileXYZ
from View.Geometry.UndoCommand import *

logger = logging.getLogger()

_translate = QCoreApplication.translate


class GeometryReachTableModel(PamhyrTableModel):
    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid():
            return QVariant()

        if role == Qt.DisplayRole and index.column() == 0:
            return self._data.profile(index.row()).name

        if role == Qt.DisplayRole and index.column() == 1:
            kp = self._data.profile(index.row()).kp
            return f"{kp:.4f}"

        if role == Qt.DisplayRole and index.column() == 2:
            return self._data.profile(index.row()).profile_type

        if role == Qt.TextAlignmentRole:
            return Qt.AlignHCenter | Qt.AlignVCenter

        if role == Qt.ForegroundRole and index.column() == 0:
            name = self._data.profile(index.row()).name\
                .strip()\
                .lower()
            if (name == "upstream" or name == "up" or
                    name == _translate("Geometry", "upstream")):
                return QColor("Green")
            elif (name == "downstream" or name == "down" or
                  name == _translate("Geometry", "downstream")):
                return QColor("Red")

        return QVariant()

    def setData(self, index, value, role=Qt.EditRole):
        row = index.row()
        column = index.column()

        if role == Qt.EditRole and index.column() != 2:
            try:
                if index.column() == 0:
                    self._undo.push(
                        SetNameCommand(
                            self._data, index.row(),
                            self._data.profile(index.row()).name,
                            value
                        )
                    )

                if index.column() == 1:
                    self._undo.push(
                        SetKPCommand(
                            self._data, index.row(),
                            self._data.profile(index.row()).kp,
                            value
                        )
                    )
            except Exception as e:
                logger.info(e)
                logger.debug(traceback.format_exc())

            self.dataChanged.emit(index, index)
            self.layoutChanged.emit()

            return True

        self.dataChanged.emit(index, index)
        self.layoutChanged.emit()

        return False

    # @QtCore.pyqtSlot()
    def add(self, row, parent=QModelIndex()):
        self.beginInsertRows(parent, row, row - 1)

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

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

    def delete(self, rows, parent=QModelIndex()):
        self.beginRemoveRows(parent, rows[0], rows[-1])

        self._undo.push(
            DelCommand(
                self._data, rows
            )
        )

        self.endRemoveRows()
        self.layoutChanged.emit()

    def sort_profiles(self, _reverse):
        self.layoutAboutToBeChanged.emit()

        self._undo.push(
            SortCommand(
                self._data, _reverse
            )
        )

        self.layoutAboutToBeChanged.emit()
        self.layoutChanged.emit()

    def move_up(self, row, parent=QModelIndex()):
        if row <= 0:
            return

        target = row + 2

        self.beginMoveRows(parent, row - 1, row - 1, parent, target)

        self._undo.push(
            MoveCommand(
                self._data, "up", row
            )
        )

        self.endMoveRows()
        self.layoutChanged.emit()

    def move_down(self, row, parent=QModelIndex()):
        if row > self._data.number_profiles:
            return

        target = row

        self.beginMoveRows(parent, row + 1, row + 1, parent, target)

        self._undo.push(
            MoveCommand(
                self._data, "down", row
            )
        )

        self.endMoveRows()
        self.layoutChanged.emit()

    def duplicate(self, rows, profiles):
        self.layoutAboutToBeChanged.emit()

        self._undo.push(
            DuplicateCommand(
                self._data, rows,
                profiles
            )
        )

        self.layoutAboutToBeChanged.emit()
        self.layoutChanged.emit()

    def paste(self, row, header, data):
        if row > self._data.number_profiles:
            return

        if len(data) == 0:
            return

        self.layoutAboutToBeChanged.emit()

        self._undo.push(
            PasteCommand(
                self._data, row,
                list(
                    map(
                        lambda d: ProfileXYZ.from_data(header, d),
                        data
                    )
                )
            )
        )

        self.layoutAboutToBeChanged.emit()
        self.layoutChanged.emit()
