# 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, rep_line, **kwargs):
        QUndoCommand.__init__(self)

        self._rep_line = rep_line
        self._new = kwargs
        self._old = None

    def undo(self):
        f = self._rep_line

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

    def redo(self):
        f = self._rep_line

        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, lines, row):
        QUndoCommand.__init__(self)

        self._lines = lines
        self._row = row
        self._new = None

    def undo(self):
        self._lines.delete([self._new])

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


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

        self._lines = lines
        self._row = row
        self._old = self._lines.get(row)

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

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