001package jmri.jmrit.operations.routes.tools;
002
003import java.io.*;
004import java.nio.charset.StandardCharsets;
005
006import org.apache.commons.csv.CSVFormat;
007import org.apache.commons.csv.CSVPrinter;
008
009import jmri.InstanceManager;
010import jmri.jmrit.XmlFile;
011import jmri.jmrit.operations.routes.*;
012import jmri.jmrit.operations.setup.OperationsSetupXml;
013import jmri.util.swing.JmriJOptionPane;
014
015/**
016 * Export Routes to CSV file
017 */
018public class ExportRoutes extends XmlFile {
019
020    public ExportRoutes() {
021        // nothing to do
022    }
023
024    public void writeOperationsRoutesFile() {
025        makeBackupFile(defaultOperationsFilename());
026        try {
027            if (!checkFile(defaultOperationsFilename())) {
028                // The file does not exist, create it before writing
029                java.io.File file = new java.io.File(defaultOperationsFilename());
030                java.io.File parentDir = file.getParentFile();
031                if (!parentDir.exists()) {
032                    if (!parentDir.mkdir()) {
033                        log.error("Directory wasn't created");
034                    }
035                }
036                if (file.createNewFile()) {
037                    log.debug("File created");
038                }
039            }
040            writeFile(defaultOperationsFilename());
041        } catch (IOException e) {
042            log.error("Exception while writing the new CSV operations file, may not be complete: {}",
043                    e.getLocalizedMessage());
044        }
045    }
046
047    public void writeFile(String name) {
048        log.debug("writeFile {}", name);
049        // This is taken in large part from "Java and XML" page 368
050        File file = findFile(name);
051        if (file == null) {
052            file = new File(name);
053        }
054
055        int count = 0;
056        try (CSVPrinter fileOut = new CSVPrinter(
057                new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)),
058                CSVFormat.DEFAULT)) {
059
060            loadHeader(fileOut);
061
062            for (Route route : InstanceManager.getDefault(RouteManager.class).getRoutesByNameList()) {
063                count++;
064                fileOut.printRecord(route.getName(),
065                        "",
066                        route.getComment());
067                for (RouteLocation rl : route.getLocationsBySequenceList()) {
068                    if (rl.getLocation() != null) {
069                        fileOut.printRecord("",
070                                rl.getLocation().getName(),
071                                rl.getTrainDirectionString(),
072                                rl.getMaxCarMoves(),
073                                rl.getRandomControl(),
074                                rl.isPickUpAllowed() ? Bundle.getMessage("yes") : Bundle.getMessage("no"),
075                                rl.isDropAllowed() ? Bundle.getMessage("yes") : Bundle.getMessage("no"),
076                                rl.getWait(),
077                                rl.getFormatedDepartureTime(),
078                                rl.getMaxTrainLength(),
079                                rl.getGrade(),
080                                rl.getTrainIconX(),
081                                rl.getTrainIconY(),
082                                rl.getComment().replace("\n", "<LF>"),
083                                rl.getCommentTextColor());
084                    } else {
085                        fileOut.printRecord("",
086                                Bundle.getMessage("ErrorTitle"));
087                    }
088                }
089            }
090
091            JmriJOptionPane.showMessageDialog(null,
092                    Bundle.getMessage("ExportedRoutesToFile",
093                            count, defaultOperationsFilename()),
094                    Bundle.getMessage("ExportComplete"), JmriJOptionPane.INFORMATION_MESSAGE);
095
096            fileOut.flush();
097            fileOut.close();
098        } catch (IOException e) {
099            log.error("Can not open export Routes CSV file: {}", e.getLocalizedMessage());
100            JmriJOptionPane.showMessageDialog(null,
101                    Bundle.getMessage("ExportedRoutesToFile",
102                            0, defaultOperationsFilename()),
103                    Bundle.getMessage("ExportFailed"), JmriJOptionPane.ERROR_MESSAGE);
104        }
105    }
106
107    private void loadHeader(CSVPrinter fileOut) throws IOException {
108        fileOut.printRecord(Bundle.getMessage("Route"),
109                Bundle.getMessage("Location"),
110                Bundle.getMessage("TrainDirection"),
111                Bundle.getMessage("Moves"),
112                Bundle.getMessage("Random"),
113                Bundle.getMessage("Pickups"),
114                Bundle.getMessage("Drops"),
115                Bundle.getMessage("Travel"),
116                Bundle.getMessage("DepartTime"),
117                Bundle.getMessage("MaxLength"),
118                Bundle.getMessage("Grade"),
119                Bundle.getMessage("X"),
120                Bundle.getMessage("Y"),
121                Bundle.getMessage("Comment"),
122                Bundle.getMessage("TextColor"));
123    }
124
125    public File getExportFile() {
126        return findFile(defaultOperationsFilename());
127    }
128
129    // Operation files always use the same directory
130    public static String defaultOperationsFilename() {
131        return OperationsSetupXml.getFileLocation()
132                + OperationsSetupXml.getOperationsDirectoryName()
133                + File.separator
134                + getOperationsFileName();
135    }
136
137    public static void setOperationsFileName(String name) {
138        operationsFileName = name;
139    }
140
141    public static String getOperationsFileName() {
142        return operationsFileName;
143    }
144
145    private static String operationsFileName = "ExportOperationsRoutes.csv"; // NOI18N
146
147    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ExportRoutes.class);
148
149}