# UndoCommand.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 -*-

from tools import trace, timer

from PyQt5.QtWidgets import (
    QMessageBox, QUndoCommand, QUndoStack,
)


class SetCommand(QUndoCommand):
    def __init__(self, geotiff, **kwargs):
        QUndoCommand.__init__(self)

        self._geotiff = geotiff
        self._new = kwargs
        self._old = None

    def undo(self):
        f = self._geotiff

        for key in self._old:
            f[key] = self._old[key]

    def redo(self):
        f = self._geotiff

        if self._old is None:
            self._old = {}
            for key in self._new:
                self._old[key] = f[key]

        for key in self._new:
            f[key] = self._new[key]


class AddCommand(QUndoCommand):
    def __init__(self, files, row):
        QUndoCommand.__init__(self)

        self._files = files
        self._row = row
        self._new = None

    def undo(self):
        self._new.set_as_deleted()

    def redo(self):
        if self._new is None:
            self._new = self._files.new(self._row)
        else:
            self._new.set_as_not_deleted()


class DelCommand(QUndoCommand):
    def __init__(self, files, line):
        QUndoCommand.__init__(self)

        self._files = files
        self._line = line

    def undo(self):
        self._line.set_as_not_deleted()

    def redo(self):
        self._line.set_as_deleted()
