/*
 * Copyright 2015-2016 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.junit.gen5.console.options;

import static org.junit.gen5.commons.meta.API.Usage.Internal;

import java.io.IOException;
import java.io.Writer;

import joptsimple.BuiltinHelpFormatter;
import joptsimple.OptionParser;
import joptsimple.OptionSet;

import org.junit.gen5.commons.JUnitException;
import org.junit.gen5.commons.meta.API;

@API(Internal)
public class JOptSimpleCommandLineOptionsParser implements CommandLineOptionsParser {

	@Override
	public CommandLineOptions parse(String... arguments) {
		AvailableOptions availableOptions = getAvailableOptions();
		OptionParser parser = availableOptions.getParser();
		OptionSet detectedOptions = parser.parse(arguments);
		return availableOptions.toCommandLineOptions(detectedOptions);
	}

	@Override
	public void printHelp(Writer writer) {
		OptionParser optionParser = getAvailableOptions().getParser();
		optionParser.formatHelpWith(new BuiltinHelpFormatter(100, 4));
		try {
			optionParser.printHelpOn(writer);
		}
		catch (IOException e) {
			throw new JUnitException("Error printing help", e);
		}
	}

	private AvailableOptions getAvailableOptions() {
		return new AvailableOptions();
	}

}

@@ -461,16 +461,70 @@
 .Writer;
+%0Aimport java.util.LinkedHashSet;%0Aimport java.util.Map;
 %0A%0Aimport
@@ -553,24 +553,60 @@
 pFormatter;%0A
+import joptsimple.OptionDescriptor;%0A
 import jopts
@@ -1300,23 +1300,31 @@
 ith(new 
-Built
+OrderPreserv
 in
+g
 HelpForm
@@ -1333,14 +1333,8 @@
 ter(
-100, 4
 ));%0A
@@ -1558,10 +1558,342 @@
 ();%0A%09%7D%0A%0A
+%09private static final class OrderPreservingHelpFormatter extends BuiltinHelpFormatter %7B%0A%0A%09%09private OrderPreservingHelpFormatter() %7B%0A%09%09%09super(100, 4);%0A%09%09%7D%0A%0A%09%09@Override%0A%09%09public String format(Map%3CString, ? extends OptionDescriptor%3E options) %7B%0A%09%09%09addRows(new LinkedHashSet%3C%3E(options.values()));%0A%09%09%09return formattedHelpOutput();%0A%09%09%7D%0A%09%7D%0A
 %7D%0A

Print ConsoleRunner options in their declared order