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