# UndoCommand.py -- Pamhyr
# Copyright (C) 2024  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, add_file, **kwargs):
        QUndoCommand.__init__(self)

        self._add_file = add_file
        self._new = kwargs
        self._old = None

    def undo(self):
        f = self._add_file

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

    def redo(self):
        f = self._add_file

        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._files.delete([self._new])

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


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

        self._files = files
        self._row = row
        self._old = self._files.get(row)

    def undo(self):
        self._files.insert(self._row, self._old)

    def redo(self):
        self._files.delete_i([self._row])