package de.renew.unify;

import java.util.Vector;

/**
 * This class records state changes and allows them to be restored to a previous checkpoint.
 * <p>
 * Each change is represented by a {@link StateRestorer}, which can restore
 * the state before the change.
 */
public class StateRecorder implements IStateRecorder {
    /** Stores changes to the state that can be reverted. */
    private final Vector<StateRestorer> _savedObjects;

    /**
     * Constructor for the StateRecorder.
     * Initializes an empty structure to record the states.
     */
    public StateRecorder() {
        _savedObjects = new Vector<>();
    }

    @Override
    public void record(StateRestorer obj) {
        _savedObjects.addElement(obj);
    }

    @Override
    public int checkpoint() {
        return _savedObjects.size();
    }

    @Override
    public void restore(int checkpoint) {
        if (checkpoint < _savedObjects.size()) {
            for (int i = _savedObjects.size() - 1; i >= checkpoint; i--) {
                _savedObjects.elementAt(i).restore();
            }
            _savedObjects.setSize(checkpoint);
        }
    }

    @Override
    public void restore() {
        restore(0);
    }
}