001package jmri.jmrit.operations.rollingstock.engines.tools;
002
003import java.io.*;
004import java.nio.charset.StandardCharsets;
005import java.util.List;
006
007import org.apache.commons.csv.CSVFormat;
008import org.apache.commons.csv.CSVPrinter;
009
010import jmri.jmrit.XmlFile;
011import jmri.jmrit.operations.rollingstock.engines.Engine;
012import jmri.jmrit.operations.setup.OperationsSetupXml;
013import jmri.jmrit.operations.setup.Setup;
014import jmri.util.swing.JmriJOptionPane;
015
016/**
017 * Exports the Engine roster into a comma delimited file (CSV). Order stored:
018 * Number, Road, Model, Length, Owner, Built, Location, -, Track, Consist,
019 * Moves, Last, Value, HP, Weight, Type, Comment, Misc.
020 *
021 * @author Daniel Boudreau Copyright (C) 2010
022 *
023 */
024public class ExportEngines extends XmlFile {
025
026    protected static final String LOCATION_TRACK_SEPARATOR = "-";
027    List<Engine> _engineList;
028
029    public ExportEngines(List<Engine> engineList) {
030        _engineList = engineList;
031    }
032
033    /**
034     * Store the all of the operation Engine objects in the default place,
035     * including making a backup if needed
036     */
037    public void writeOperationsEngineFile() {
038        makeBackupFile(defaultOperationsFilename());
039        try {
040            if (!checkFile(defaultOperationsFilename())) {
041                // The file does not exist, create it before writing
042                java.io.File file = new java.io.File(defaultOperationsFilename());
043                java.io.File parentDir = file.getParentFile();
044                if (!parentDir.exists()) {
045                    if (!parentDir.mkdir()) {
046                        log.error("Directory wasn't created");
047                    }
048                }
049                if (file.createNewFile()) {
050                    log.debug("File created");
051                }
052            }
053            writeFile(defaultOperationsFilename());
054        } catch (IOException e) {
055            log.error("Exception while writing the new CSV operations file, may not be complete: {}",
056                    e.getLocalizedMessage());
057        }
058    }
059
060    public void writeFile(String name) {
061        log.debug("writeFile {}", name);
062        // This is taken in large part from "Java and XML" page 368
063        File file = findFile(name);
064        if (file == null) {
065            file = new File(name);
066        }
067
068        try (CSVPrinter fileOut = new CSVPrinter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)),
069                CSVFormat.DEFAULT)) {
070
071            // create header
072            fileOut.printRecord(Bundle.getMessage("Number"),
073                    Bundle.getMessage("Road"),
074                    Bundle.getMessage("Model"),
075                    Bundle.getMessage("Length"),
076                    Bundle.getMessage("Owner"),
077                    Bundle.getMessage("Built"),
078                    Bundle.getMessage("Location"),
079                    LOCATION_TRACK_SEPARATOR,
080                    Bundle.getMessage("Track"),
081                    Bundle.getMessage("Consist"),
082                    Bundle.getMessage("Moves"),
083                    Bundle.getMessage("Last"),
084                    Setup.getValueLabel(),
085                    Bundle.getMessage("HP"),
086                    Bundle.getMessage("WeightTons"),
087                    Bundle.getMessage("Type"),
088                    Bundle.getMessage("Comment"),
089                    Bundle.getMessage("Miscellaneous"));
090
091            // store engine number, road, model, length, owner, built date, location - track
092            for (Engine engine : _engineList) {
093                fileOut.printRecord(engine.getNumber(),
094                        engine.getRoadName(),
095                        engine.getModel(),
096                        engine.getLength(),
097                        engine.getOwnerName(),
098                        engine.getBuilt(),
099                        engine.getLocationName(),
100                        LOCATION_TRACK_SEPARATOR,
101                        engine.getTrackName(),
102                        engine.getConsistName(),
103                        engine.getMoves(),
104                        engine.getSortDate(),
105                        engine.getValue(),
106                        engine.getHp(),
107                        engine.getWeightTons(),
108                        engine.getTypeName(),
109                        engine.getComment(),
110                        engine.isOutOfService() ? Bundle.getMessage("OutOfService") : "");
111            }
112            log.info("Exported {} engines to file {}", _engineList.size(), defaultOperationsFilename());
113            JmriJOptionPane.showMessageDialog(null, Bundle.getMessage("ExportedEnginesToFile",
114                    _engineList.size(), defaultOperationsFilename()), Bundle.getMessage("ExportComplete"),
115                    JmriJOptionPane.INFORMATION_MESSAGE);
116        } catch (IOException e) {
117            log.error("Can not open export engines CSV file: {}", e.getLocalizedMessage());
118            JmriJOptionPane.showMessageDialog(null, Bundle.getMessage("ExportedEnginesToFile",
119                    0, defaultOperationsFilename()), Bundle.getMessage("ExportFailed"),
120                    JmriJOptionPane.ERROR_MESSAGE);
121        }
122    }
123
124    // Operation files always use the same directory
125    public static String defaultOperationsFilename() {
126        return OperationsSetupXml.getFileLocation()
127                + OperationsSetupXml.getOperationsDirectoryName()
128                + File.separator
129                + getOperationsFileName();
130    }
131
132    public static void setOperationsFileName(String name) {
133        operationsFileName = name;
134    }
135
136    public static String getOperationsFileName() {
137        return operationsFileName;
138    }
139
140    private static String operationsFileName = "ExportOperationsEngineRoster.csv"; // NOI18N
141
142    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ExportEngines.class);
143
144}