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", e);
043        }
044    }
045
046    public void writeFile(String name) {
047        log.debug("writeFile {}", name);
048        // This is taken in large part from "Java and XML" page 368
049        File file = findFile(name);
050        if (file == null) {
051            file = new File(name);
052        }
053
054        int count = 0;
055        try (CSVPrinter fileOut = new CSVPrinter(
056                new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)),
057                CSVFormat.DEFAULT)) {
058
059            loadHeader(fileOut);
060
061            for (Route route : InstanceManager.getDefault(RouteManager.class).getRoutesByNameList()) {
062                count++;
063                fileOut.printRecord(route.getName(),
064                        "",
065                        route.getComment());
066                for (RouteLocation rl : route.getLocationsBySequenceList()) {
067                    if (rl.getLocation() != null) {
068                        fileOut.printRecord("",
069                                rl.getLocation().getName(),
070                                rl.getTrainDirectionString(),
071                                rl.getMaxCarMoves(),
072                                rl.getRandomControl(),
073                                rl.isPickUpAllowed() ? Bundle.getMessage("yes") : Bundle.getMessage("no"),
074                                rl.isDropAllowed() ? Bundle.getMessage("yes") : Bundle.getMessage("no"),
075                                rl.getWait(),
076                                rl.getFormatedDepartureTime(),
077                                rl.getMaxTrainLength(),
078                                rl.getGrade(),
079                                rl.getTrainIconX(),
080                                rl.getTrainIconY(),
081                                rl.getComment().replace("\n", "<LF>"),
082                                rl.getCommentTextColor());
083                    } else {
084                        fileOut.printRecord("",
085                                Bundle.getMessage("ErrorTitle"));
086                    }
087                }
088            }
089
090            JmriJOptionPane.showMessageDialog(null,
091                    Bundle.getMessage("ExportedRoutesToFile",
092                            count, defaultOperationsFilename()),
093                    Bundle.getMessage("ExportComplete"), JmriJOptionPane.INFORMATION_MESSAGE);
094
095            fileOut.flush();
096            fileOut.close();
097        } catch (IOException e) {
098            log.error("Can not open export Routes CSV file: {}", file.getName());
099            JmriJOptionPane.showMessageDialog(null,
100                    Bundle.getMessage("ExportedRoutesToFile",
101                            0, defaultOperationsFilename()),
102                    Bundle.getMessage("ExportFailed"), JmriJOptionPane.ERROR_MESSAGE);
103        }
104    }
105
106    private void loadHeader(CSVPrinter fileOut) throws IOException {
107        fileOut.printRecord(Bundle.getMessage("Route"),
108                Bundle.getMessage("Location"),
109                Bundle.getMessage("TrainDirection"),
110                Bundle.getMessage("Moves"),
111                Bundle.getMessage("Random"),
112                Bundle.getMessage("Pickups"),
113                Bundle.getMessage("Drops"),
114                Bundle.getMessage("Wait"),
115                Bundle.getMessage("DepartTime"),
116                Bundle.getMessage("MaxLength"),
117                Bundle.getMessage("Grade"),
118                Bundle.getMessage("X"),
119                Bundle.getMessage("Y"),
120                Bundle.getMessage("Comment"),
121                Bundle.getMessage("TextColor"));
122    }
123
124    public File getExportFile() {
125        return findFile(defaultOperationsFilename());
126    }
127
128    // Operation files always use the same directory
129    public static String defaultOperationsFilename() {
130        return OperationsSetupXml.getFileLocation()
131                + OperationsSetupXml.getOperationsDirectoryName()
132                + File.separator
133                + getOperationsFileName();
134    }
135
136    public static void setOperationsFileName(String name) {
137        operationsFileName = name;
138    }
139
140    public static String getOperationsFileName() {
141        return operationsFileName;
142    }
143
144    private static String operationsFileName = "ExportOperationsRoutes.csv"; // NOI18N
145
146    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ExportRoutes.class);
147
148}