/* Copyright (c) 2015, Julien Rialland
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 * 
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 */
package com.github.jrialland.javaformatter;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.cli.CommandLine;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.jrialland.javaformatter.java.JavaFormatter;
import com.github.jrialland.javaformatter.web.CssFormatter;
import com.github.jrialland.javaformatter.web.HtmlFormatter;
import com.github.jrialland.javaformatter.web.JsFormatter;
import com.github.jrialland.javaformatter.xml.XmlFormatter;

public class FormatterCli {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(FormatterCli.class);

	protected static void showHelp(Options opts) {
		HelpFormatter helpFormatter = new HelpFormatter();
		helpFormatter.printHelp(FormatterCli.class.getSimpleName(), opts);
		return;
	}

	public static void main(String[] args) throws Exception {

		Options opts = new Options();

		Option conf = Option.builder("c").longOpt("conf").required(false).numberOfArgs(1)
				.desc("Eclipse configuration file to use").argName("eclipseConf").build();
		opts.addOption(conf);

		Option level = Option.builder("l").longOpt("level").required(false).numberOfArgs(1).argName("javaVersion")
				.desc("source level").build();
		opts.addOption(level);

		Option header = Option.builder("H").longOpt("header").required(false).numberOfArgs(1).argName("txtFile")
				.desc("source file header").build();
		opts.addOption(header);

		Option encoding = Option.builder("e").longOpt("encoding").required(false).numberOfArgs(1).argName("charset")
				.desc("source encoding").build();
		opts.addOption(encoding);

		Option lsep = Option.builder("s").longOpt("linesep").required(false).hasArg(true).argName("crlf_value").build();
		opts.addOption(lsep);

		Option help = Option.builder("h").longOpt("help").hasArg(false).desc("Shows this help").build();
		opts.addOption(help);

		CommandLine cmd = new DefaultParser().parse(opts, args);

		if (cmd.hasOption("help")) {
			showHelp(opts);
			return;
		}

		JavaFormatter javaFormatter;

		if (cmd.hasOption("conf")) {
			javaFormatter = new JavaFormatter(Paths.get(cmd.getOptionValue("conf")).toUri().toURL());
		} else {
			javaFormatter = new JavaFormatter();
		}

		if (cmd.hasOption("level")) {
			javaFormatter.setSource(cmd.getOptionValue("level"));
		}

		if (cmd.hasOption("encoding")) {
			javaFormatter.setEncoding(cmd.getOptionValue("encoding"));
		}

		if (cmd.hasOption("linesep")) {
			String linesep = cmd.getOptionValue("linesep");
			if (!Arrays.asList("lf", "cr", "crlf").contains(linesep)) {
				throw new IllegalArgumentException("linesep");
			}
			linesep = linesep.toLowerCase().replaceAll("cr", "\r").replaceAll("lf", "\n");
			javaFormatter.setLineSep(linesep);
		}

		if (cmd.hasOption("header")) {
			javaFormatter.setHeader(Paths.get(cmd.getOptionValue("header")).toUri().toURL());
		}

		Path path = Paths.get(args[args.length - 1]);

		if (args.length == 0) {
			System.out.println("Missing file or directory parameter.");
			showHelp(opts);
			System.exit(255);
		}

		List<SourceFormatter> formatters = new ArrayList<>();
		formatters.add(javaFormatter);
		formatters.addAll(Arrays.asList(new HtmlFormatter(), new CssFormatter(), new JsFormatter(), new XmlFormatter()));

		if(LOGGER.isDebugEnabled()) {
			LOGGER.debug("Registered formatters : ");
			for(SourceFormatter fmt : formatters) {
				LOGGER.debug("\t- " + fmt.getName());
			}
		}
				
		FormatterVisitor visitor = new FormatterVisitor(formatters);

		if (Files.isRegularFile(path)) {
			visitor.applyAllOnFile(path);
		} else if (Files.isDirectory(path)) {
			visitor.visit(path);
		} else {
			throw new IllegalArgumentException("File or Directory not found : " + path);
		}

	}
}

@@ -4539,53 +4539,8 @@
 %0A%0A%09%09
-Path path = Paths.get(args%5Bargs.length - 1%5D);
 %0A%0A%09%09
@@ -4670,16 +4670,69 @@
 5);%0A%09%09%7D%0A
+%09%09%0A%09%09Path path = Paths.get(args%5Bargs.length - 1%5D);%0A%09%09
 %0A%09%09List%3C

check command args length earlier