package eu.simstadt.regionchooser;

import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Callable;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;


@Command(name = "region_chooser", mixinStandardHelpOptions = true, version = "regionChooser x.x", description = "Extracts a region from one or more citygmls.", sortOptions = false)
class RegionChooserCommandLineInterface implements Callable<Integer>
{
	@Option(names = { "-i",
			"--input" }, required = true, split = ",", description = "Citygml files to extract from", paramLabel = "input.gml")
	List<Path> citygmls;

	@Option(names = { "-o",
			"--output" }, required = true, description = "Output file", paramLabel = "output.gml")
	Path outputCityGML;

	@Option(names = { "-e", "--epsg" }, description = "EPSG id for coordinate reference system", paramLabel = "31467")
	Integer espgId;

	@Option(names = { "-w",
			"--wkt" }, description = "File containing WKT polygon, or - for stdin", paramLabel = "polygon.wkt")
	String wktFile = "-";

	@Override
	public Integer call() throws Exception { // your business logic goes here...
		System.out.println("Should extract from :");
		for (Path input_citygml : citygmls) {
			System.out.println("  " + input_citygml);
		}
		System.out.print("And write to : ");
		System.out.println(outputCityGML);
		try (BufferedWriter bf = Files.newBufferedWriter(outputCityGML)) {
			bf.write("HELLO THERE!");
		}
		if (espgId == null) {
			System.out.println("coordinates from " + citygmls.get(0));
		} else {
			System.out.print("in EPSG:");
			System.out.println(espgId + " coordinates.");
		}

		if (wktFile.equals("-")) {
			if (System.in.available() == 0) {
				System.out.println("OH NOEs, NO INPUT!");
			} else {
				System.out.println("Here's standard input:");
				System.out.println(getInput());
				System.out.println("Done");
			}
		} else {
			System.out.println("Try to read from " + wktFile);
		}

		return 0;
	}

	private static String getInput() {
		try (Scanner myObj = new Scanner(System.in)) {
			return myObj.nextLine();
		}
	}

	// this example implements Callable, so parsing, error handling and handling user
	// requests for usage help or version help can be done with one line of code.
	public static void main(String... args) {
		int exitCode = new CommandLine(new RegionChooserCommandLineInterface()).execute(args);
		System.exit(exitCode);
	}
}