package leigh.gis.gpx;

import io.jenetics.jpx.GPX;
import io.jenetics.jpx.Track;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.util.UniversalJob;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * Utility to extract tracks from a monolithic GPX file into multiple GPX files.
 *
 * @author Alex Leigh
 */
public class TrackExtractor {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(TrackExtractor.class);

    public static void main(String[] args) throws IOException {
        UniversalJob.banner(logger, "TrackExtractor");

        if (args.length != 1) {
            logger.error("Usage: TrackExtractor file.gpx");
            System.exit(UniversalJob.RET_BADARGS);
        }

        GPX gpx = GPX.read(args[0]);

        logger.info("Loaded GPX file.");

        for (Track track : gpx.getTracks()) {
            GPX trackGpx = GPX.builder().addTrack(track).build();
            String filename = track.getName() + ".gpx";
            logger.info("Writing track: [name: {}]", track.getName());
            GPX.write(trackGpx, Paths.get(filename));
        }
    }
}
