/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.config.tenant.commands;

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.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * This class contains contains methods to convert the inline commands into Java objects.
 */
public class MainParametersProcessor {

	private static final Logger LOG = LoggerFactory.getLogger(MainParametersProcessor.class);
	
	/**
	 * Non-public constructor
	 */
	private MainParametersProcessor() {
	}
	
    /**
     * Gets a raw command line and process into a {@link Command}.
     *
     * @param args a raw command line
     * @return the {@link Command} that represents the raw command line, {@code null} if the raw command line cannot be
     * processed.
     */
    public static Command process(final String[] args) {

        final Options options = generateOptions();

        final DefaultParser parser = new DefaultParser();

        final CommandLine cmd;

        try {
            cmd = parser.parse(options, args);
        } catch (final ParseException e) {
            printHelp(options);
            return null;
        }

        MutuallyExclusiveCommand mutuallyExclusiveCommand = null;

        if (cmd.hasOption(MutuallyExclusiveCommand.HELP.getCommandName())) {
            mutuallyExclusiveCommand = MutuallyExclusiveCommand.HELP;

            printHelp(options);
        } else {
            final Option[] optionVector = cmd.getOptions();
            for (final MutuallyExclusiveCommand command : MutuallyExclusiveCommand.values()) {
                if (ArrayUtils.contains(optionVector, command.generateOption())) {
                    mutuallyExclusiveCommand = command;
                    break;
                }
            }
        }

        final Parameters commandParams = new Parameters();
        addValueToParameters(commandParams, cmd, mutuallyExclusiveCommand);

        return new Command(mutuallyExclusiveCommand, commandParams);
    }

    private static void addValueToParameters(final Parameters commandParams, final CommandLine cmd,
            final MutuallyExclusiveCommand command) {
        for (final CommandParameter commandParameter : command.getCommandParameters()) {
            // validate param required
            final String optionName = commandParameter.getParameterName();
            final String[] optionValues = cmd.getOptionValues(optionName);
            String optionValue = null;
            if (!ArrayUtils.isEmpty(optionValues)) {
                optionValue = String.join(",", optionValues);
            }
            if (commandParameter.isRequired() && StringUtils.isEmpty(optionValue)) {
                throw new IllegalArgumentException(String.format("%s command requires %s parameter.",
                        command.getCommandName(), optionName));
            }
            if (commandParameter.getNumberOfArgs() > 0
                    || commandParameter.getNumberOfArgs() == Option.UNLIMITED_VALUES) {
                commandParams.addParam(optionName, optionValue);
            } else {
                // parameters without value, like flags
                commandParams.addParam(optionName, String.valueOf(true));
            }
        }
    }

    private static Options generateOptions() {
        final Options options = new Options();
        final OptionGroup mainCommands = MutuallyExclusiveCommand.getCommandsOptionGroup();
        mainCommands.setRequired(true);

        options.addOptionGroup(mainCommands);

        for (final CommandParameter commandParameter : CommandParameter.values()) {
            options.addOption(commandParameter.generateOption());
        }
        return options;
    }

    private static void printHelp(final Options options) {

        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("program", options, true);

        try (InputStream is = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream("config-tenant.help.txt");
             PrintWriter pw = new PrintWriter(System.out)) {
            IOUtils.copy(is, pw);
        } catch (final IOException e) {
            LOG.warn("A error occurred when trying to print extend help.", e);
        }

    }

}
