001package jmri.jmrit.operations.setup;
002
003import org.slf4j.Logger;
004import org.slf4j.LoggerFactory;
005
006import jmri.InstanceManager;
007import jmri.jmrit.operations.OperationsXml;
008import jmri.jmrit.operations.trains.TrainManager;
009
010/**
011 * Auto Save. When enabled will automatically save operation files.
012 *
013 * @author Daniel Boudreau Copyright (C) 2012
014 */
015public class AutoSave {
016
017    static Thread autoSave = null;
018
019    public static synchronized void start() {
020        if (Setup.isAutoSaveEnabled() && autoSave == null) {
021            autoSave = jmri.util.ThreadingUtil.newThread(() -> {
022                saveFiles();
023            });
024            autoSave.setName("Operations Auto Save"); // NOI18N
025            autoSave.start();
026        }
027    }
028
029    public static synchronized void stop() {
030        if (autoSave != null) {
031            autoSave.interrupt();
032            autoSave = null;
033        }
034    }
035
036    @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( value="SLF4J_FORMAT_SHOULD_BE_CONST",
037            justification="I18N of Info Message")
038    private static void saveFiles() {
039        while (true) {
040            synchronized (autoSave) {
041                if (!Setup.isAutoSaveEnabled()) {
042                    break;
043                }
044                try {
045                    autoSave.wait(60000); // check every minute
046                } catch (InterruptedException e) {
047                    break; // stop was called
048                }
049                if (OperationsXml.areFilesDirty()) {
050                    log.debug("Detected dirty operation files");
051                    try {
052                        autoSave.wait(60000); // wait another minute before
053                                              // saving
054                    } catch (InterruptedException e) {
055                        //do nothing
056                    }
057                    if (!Setup.isAutoSaveEnabled()) {
058                        break;
059                    }
060                    if (InstanceManager.getDefault(TrainManager.class).isAnyTrainBuilding()) {
061                        log.debug("Detected trains being built");
062                        continue;
063                    }
064                    if (OperationsXml.areFilesDirty()) {
065                        OperationsXml.save();
066                        log.info(Bundle.getMessage("InfoFilesSaved"));
067                    }
068                }
069            }
070        }
071        autoSave = null; // done
072    }
073
074    private final static Logger log = LoggerFactory.getLogger(AutoSave.class);
075}