001package jmri.jmrit.operations.locations.schedules.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.InstanceManager;
011import jmri.jmrit.XmlFile;
012import jmri.jmrit.operations.locations.Track;
013import jmri.jmrit.operations.locations.schedules.*;
014import jmri.jmrit.operations.setup.OperationsSetupXml;
015import jmri.util.swing.JmriJOptionPane;
016
017/**
018 * Exports the Operation Schedules into a comma delimited file (CSV).
019 *
020 * @author Daniel Boudreau Copyright (C) 2018
021 */
022public class ExportSchedules extends XmlFile {
023
024    public void writeOperationsScheduleFile() {
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        File file = findFile(name);
050        if (file == null) {
051            file = new File(name);
052        }
053
054        try (CSVPrinter fileOut = new CSVPrinter(
055                new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)),
056                CSVFormat.DEFAULT)) {
057
058            // create header
059            fileOut.printRecord(Bundle.getMessage("ScheduleName"),
060                    Bundle.getMessage("Id"),
061                    Bundle.getMessage("Type"),
062                    Bundle.getMessage("Random"),
063                    Bundle.getMessage("Delivery"),
064                    Bundle.getMessage("Road"),
065                    Bundle.getMessage("Receive"),
066                    Bundle.getMessage("Ship"),
067                    Bundle.getMessage("Destination"),
068                    Bundle.getMessage("Track"),
069                    Bundle.getMessage("Pickup"),
070                    Bundle.getMessage("Count"),
071                    Bundle.getMessage("Wait"),
072                    Bundle.getMessage("Hits"),
073                    Bundle.getMessage("Comment"),
074                    Bundle.getMessage("Number"),
075                    Bundle.getMessage("Location"),
076                    Bundle.getMessage("Spur"),
077                    Bundle.getMessage("ScheduleMode"));
078
079            ScheduleManager scheduleManager = InstanceManager.getDefault(ScheduleManager.class);
080            List<Schedule> schedules = scheduleManager.getSchedulesByNameList();
081            for (Schedule schedule : schedules) {
082                List<Track> spurs = scheduleManager.getListSpurs(schedule);
083                int size = spurs.size();
084                for (ScheduleItem scheduleItem : schedule.getItemsBySequenceList()) {
085                    // list each location, track, and mode for this schedule
086                    String num = "";
087                    String locationName = "";
088                    String spurName = "";
089                    String scheduleMode = "";
090                    if (size > 0) {
091                        num = Integer.toString(size);
092                        Track spur = spurs.get(--size);
093                        locationName = spur.getLocation().getName();
094                        spurName = spur.getName();
095                        scheduleMode = spur.getScheduleModeName();
096                    }
097                    fileOut.printRecord(schedule.getName(),
098                            scheduleItem.getId(),
099                            scheduleItem.getTypeName(),
100                            scheduleItem.getRandom(),
101                            scheduleItem.getSetoutTrainScheduleName(),
102                            scheduleItem.getRoadName(),
103                            scheduleItem.getReceiveLoadName(),
104                            scheduleItem.getShipLoadName(),
105                            scheduleItem.getDestinationName(),
106                            scheduleItem.getDestinationTrackName(),
107                            scheduleItem.getPickupTrainScheduleName(),
108                            scheduleItem.getCount(),
109                            scheduleItem.getWait(),
110                            scheduleItem.getHits(),
111                            schedule.getComment(),
112                            num,
113                            locationName,
114                            spurName,
115                            scheduleMode);
116                }
117            }
118            fileOut.flush();
119            fileOut.close();
120            log.info("Exported {} schedules to file {}", schedules.size(), defaultOperationsFilename());
121            JmriJOptionPane.showMessageDialog(null,
122                    Bundle.getMessage("ExportedSchedulesToFile", schedules.size(), defaultOperationsFilename()),
123                    Bundle.getMessage("ExportComplete"), JmriJOptionPane.INFORMATION_MESSAGE);
124        } catch (IOException e) {
125            log.error("Can not open export schedules CSV file: {}", e.getLocalizedMessage());
126            JmriJOptionPane.showMessageDialog(null,
127                    Bundle.getMessage("ExportedSchedulesToFile", 0, defaultOperationsFilename()),
128                    Bundle.getMessage("ExportFailed"), JmriJOptionPane.ERROR_MESSAGE);
129        }
130    }
131
132    // Operation files always use the same directory
133    public static String defaultOperationsFilename() {
134        return OperationsSetupXml.getFileLocation() +
135                OperationsSetupXml.getOperationsDirectoryName() +
136                File.separator +
137                getOperationsFileName();
138    }
139
140    public static void setOperationsFileName(String name) {
141        operationsFileName = name;
142    }
143
144    public static String getOperationsFileName() {
145        return operationsFileName;
146    }
147
148    private static String operationsFileName = "ExportOperationsSchedules.csv"; // NOI18N
149
150    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ExportSchedules.class);
151
152}