package CH.ifa.draw.util;

import java.util.Hashtable;

import de.renew.draw.storables.ontology.Drawing;


/**
 * This class manages the autosaving of drawings. For each added drawing, a separate AutosaveTask
 * is created and the drawing is registered with that AutosaveTask.
 * @deprecated This class is not to be used externally and will later be hidden.
 */
@Deprecated(since = "5.0", forRemoval = true)
public class AutosaveManager {
    private final Hashtable<Drawing, AutosaveTask> _autosaveTasks = new Hashtable<>();
    private final long _interval;
    private final AutosaveSaver _saver;

    /**
     * Constructs a new autosave manager with an AutosaveSaver
     * and an interval determining the time between saves.
     *
     * @param saver the saver used to save drawings/files
     * @param interval the interval at which the drawings/files will be saved
     */
    public AutosaveManager(AutosaveSaver saver, long interval) {
        this._saver = saver;
        this._interval = interval;
    }

    /**
     * Includes a drawing in the list of drawings to be autosaved.
     * If the drawing is already included in the list, reset
     * its last save time to now.
     *
     * @param drawing the <code>Drawing</code> to be autosaved
     */
    public synchronized void addDrawing(Drawing drawing) {
        AutosaveTask task = _autosaveTasks.get(drawing);
        if (task == null) {
            task = new AutosaveTask(_saver, drawing, _interval);
            _autosaveTasks.put(drawing, task);
        }
        task.reset();
    }

    /**
     * Excludes a drawing from the list of drawings to be autosaved.
     * Remove its autosave file, if any.
     *
     * @param drawing the <code>Drawing</code> not to be autosaved
     */
    public synchronized void removeDrawing(Drawing drawing) {
        AutosaveTask task = _autosaveTasks.get(drawing);
        if (task != null) {
            task.terminate();
            _autosaveTasks.remove(drawing);
        }
    }

    /**
     * Update the name of the autosave file associated to a
     * drawing. This method should be called after a drawing has
     * been renamed. If the name of a drawing changes without
     * calling this method, the old autosave file will still be
     * used, which is allowed.
     *
     * @param drawing the <code>Drawing</code> to be renamed
     */
    public synchronized void renameDrawing(Drawing drawing) {
        removeDrawing(drawing);
        addDrawing(drawing);
    }
}