001package jmri.jmrit.revhistory;
002
003import java.util.ArrayList;
004import jmri.InstanceManagerAutoDefault;
005
006/**
007 * Memo class to remember a file revision history.
008 * <p>
009 * These can be nested: A revision can come with a history.
010 *
011 * @author Bob Jacobsen Copyright (c) 2010
012 */
013public class FileHistory implements InstanceManagerAutoDefault {
014
015    ArrayList<OperationMemo> list = new ArrayList<>();
016
017    /**
018     * Add a revision from complete information created elsewhere.
019     *
020     * @param type     operation type
021     * @param date     operation date
022     * @param filename file operated on
023     * @param history  source history instance
024     */
025    public void addOperation(String type, String date, String filename, FileHistory history) {
026        OperationMemo r = new OperationMemo();
027        r.type = type;
028        r.date = date;
029        r.filename = filename;
030        r.history = history;
031
032        list.add(r);
033    }
034
035    public void addOperation(OperationMemo r) {
036        list.add(r);
037    }
038
039    public void addOperation(String type, String filename, FileHistory history) {
040        OperationMemo r = new OperationMemo();
041        r.type = type;
042        r.date = (new java.util.Date()).toString();
043        r.filename = filename;
044        r.history = history;
045
046        list.add(r);
047    }
048
049    /**
050     * @param keep Number of levels to keep
051     */
052    public void purge(int keep) {
053        for (int i = 0; i < list.size(); i++) {
054            OperationMemo r = list.get(i);
055            if (keep <= 1) {
056                r.history = null;
057            }
058            if (r.history != null) {
059                r.history.purge(keep - 1);
060            }
061        }
062    }
063
064    public String toString(String prefix) {
065        StringBuilder retval = new StringBuilder();
066        list.stream().forEachOrdered((r) -> {
067            retval.append(prefix).append(r.date).append(": ").append(r.type).append(" ").append(r.filename).append("\n");
068            if (r.history != null) {
069                retval.append(r.history.toString(prefix + "    "));
070            }
071        });
072        return retval.toString();
073    }
074
075    @Override
076    public String toString() {
077        return toString("");
078    }
079
080    public ArrayList<OperationMemo> getList() {
081        return list;
082    }
083
084    /**
085     * Memo class for each revision itself.
086     */
087    public class OperationMemo {
088
089        public String type;  // load, store
090        public String date;
091        public String filename;
092        public FileHistory history;  // only with load
093    }
094
095}