package com.conveyal.gtfs;

import com.conveyal.gtfs.stats.FeedStats;
import com.conveyal.gtfs.util.json.JsonManager;
import com.conveyal.gtfs.validator.model.ValidationResult;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.zip.ZipFile;

public class GTFSMain {

    private static final Logger LOG = LoggerFactory.getLogger(GTFSMain.class);

    public static void main (String[] args) throws Exception {
        Options options = getOptions();
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse( options, args);
        if (cmd.hasOption("help")) {
            printHelp(options);
            return;
        }
        if (args.length < 1) {
            System.out.println("Please specify a GTFS feed to load.");
            System.exit(1);
        }
        File tempFile = File.createTempFile("gtfs", ".db");

        GTFSFeed feed = new GTFSFeed(tempFile.getAbsolutePath());
        feed.loadFromFile(new ZipFile(args[0]));

        feed.findPatterns();
        // TODO: add way to run only specific validators
        if(cmd.hasOption("validate")) {
            feed.validate();
            JsonManager<ValidationResult> json = new JsonManager(ValidationResult.class);
            ValidationResult result = new ValidationResult(args[0], feed, new FeedStats(feed));
            File resultFile;
            if (args.length >= 2) {
                resultFile = new File(args[1]);
            } else {
                resultFile = File.createTempFile("result", ".json");
            }
            FileUtils.writeStringToFile(resultFile, json.write(result));
            LOG.info("Storing validation result at: {}", resultFile.getAbsolutePath());
        }
        feed.close();

        LOG.info("reopening feed");

        // re-open
        GTFSFeed reconnected = new GTFSFeed(tempFile.getAbsolutePath());

        LOG.info("Connected to already loaded feed");

        LOG.info("  {} routes", reconnected.routes.size());
        LOG.info("  {} trips", reconnected.trips.size());
        LOG.info("  {} stop times", reconnected.stop_times.size());
        LOG.info("  Feed ID: {}", reconnected.feedId);
    }

    private static void printHelp(Options options) {
        final String HELP = String.join("\n",
                "java -jar gtfs-lib-shaded.jar [options] INPUT.zip [result.json]",
                "Load input GTFS feed into storage-backed MapDB for use in Java-based",
                "applications. Optionally, write feed to output location. For more, see",
                "https://github.com/conveyal/gtfs-lib#gtfs-lib",
                "", // blank lines for legibility
                ""
        );
        HelpFormatter formatter = new HelpFormatter();
        System.out.println(); // blank line for legibility
        formatter.printHelp( HELP, options );
        System.out.println(); // blank line for legibility
    }

    private static Options getOptions () {
        Options options = new Options();
        Option help = new Option("help", false, "print this message");
        Option validate = new Option("validate", false, "run full validation suite on input GTFS feed (optionally store at [result.json])");
        options.addOption(help);
        options.addOption(validate);
        return options;
    }

}

@@ -895,24 +895,68 @@
 ons, args);%0A
+        String%5B%5D arguments = cmd.getArgs();%0A
         if (
@@ -1049,32 +1049,37 @@
 %0A        if (arg
+ument
 s.length %3C 1) %7B%0A
@@ -1351,24 +1351,29 @@
  ZipFile(arg
+ument
 s%5B0%5D));%0A%0A   
@@ -1676,16 +1676,21 @@
 sult(arg
+ument
 s%5B0%5D, fe
@@ -1731,60 +1731,49 @@
     
-File
+String
  result
-File;%0A            if (args.length %3E= 2) %7B
+String = json.write(result);
 %0A   
@@ -1773,35 +1773,36 @@
 t);%0A            
-   
+File
  resultFile = ne
@@ -1800,134 +1800,108 @@
 File
- = new File(args%5B1%5D);%0A            %7D else %7B%0A                resultFile = File.createTempFile(%22result%22, %22.json%22
+;%0A            if (arguments.length %3E= 2) %7B%0A                resultFile = new File(arguments%5B1%5D
 );%0A    
-  
-      %7D%0A
     
@@ -1952,29 +1952,27 @@
 le, 
-json.write(result));%0A
+resultString);%0A    
     
@@ -2047,32 +2047,191 @@
 bsolutePath());%0A
+            %7D else %7B%0A                LOG.info(%22Printing validation result for %7B%7D%22, feed.feedId);%0A                System.out.print(resultString);%0A            %7D%0A
         %7D%0A      

print validation result to stdout if no file provided