/*-
 *  Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
 * 
 *  This file is part of CityDoctor2.
 *
 *  CityDoctor2 is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  CityDoctor2 is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with CityDoctor2.  If not, see <https://www.gnu.org/licenses/>.
 */
package de.hft.stuttgart.citydoctor2.error;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * CLI utility class for handling termination reasons
 * 
 * @author Matthias Betz
 *
 */
public class ErrorHandler {

	private static final Logger LOGGER = LogManager.getLogger(ErrorHandler.class);

	private ErrorHandler() {
		// only static usage
	}

	private static final String TERMINATION_STRING = "The application has"
			+ " encountered a fatal error and is now terminating. Reason:\n";
	private static final String ENCOUNTERED_ERROR = "Encountered error:\n";

	/**
	 * Terminates the application with the given message. The message is printed to
	 * the error output stream. A stack trace is printed from the given error.
	 * 
	 * @param msg   the termination message
	 * @param error an error object, can be null.
	 */
	public static void terminateOnError(String msg, Throwable error) {
		System.err.println(TERMINATION_STRING);
		System.err.println(msg);
		if (error != null) {
			System.err.println(ENCOUNTERED_ERROR);
			LOGGER.error(msg, error);
		}
		System.exit(1);
	}

	/**
	 * Terminates the application with the given message. The message is printed to
	 * the error output stream.
	 * 
	 * @param msg the termination message
	 */
	public static void terminateOnError(String msg) {
		terminateOnError(msg, null);
	}

	/**
	 * Called when an illegal parameter has been used or wrong usage of a parameter.
	 * Prints the message to the error stream, prints the help menu to the output
	 * stream and terminates.
	 * 
	 * @param msg the message to be printed to the error stream
	 */
	public static void printHelpAndTerminate(String msg) {
		System.err.println(msg);
		printHelp();
		System.exit(1);
	}

	/**
	 * Prints the help to the output stream.
	 */
	public static void printHelp() {
		System.out.println("\nUsage: ");
		System.out.println("Mandatory parameters:");
		System.out.println("-config <filename>");
		System.out.println("\t Contains all configuration needed for checking");
	}

}
