/**
 * 
 */
package com.ejie.ad74a.context.log;

import java.io.File;
import java.io.FileNotFoundException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;

/**
 * Inicializador de logback
 * 
 * @author JBHG
 * 
 */
public abstract class LogbackConfigurer {
	public static final String CLASSPATH_URL_PREFIX = "classpath:";
	public static final String XML_FILE_EXTENSION = ".xml";
	static final Logger logger = LoggerFactory.getLogger(LogbackConfigurer.class);

	private LogbackConfigurer() {
		super();
	}

	/**
	 * 
	 * @param location
	 *            String
	 * @param printState
	 *            boolean
	 * @throws FileNotFoundException
	 *             e
	 */
	public static void initLogging(String location, boolean printState) throws FileNotFoundException {
		LogbackConfigurer.logger.trace("Begins the initialization of system logs");
		String resolvedLocation;
		File file = null;
		StringBuilder compositeLocator = new StringBuilder("classpath:");
		compositeLocator.append(location);

		if (location.contains(".xml")) {
			try {
				resolvedLocation = SystemPropertyUtils.resolvePlaceholders(compositeLocator.toString());
				file = ResourceUtils.getFile(resolvedLocation);
			} catch (FileNotFoundException e) {
				LogbackConfigurer.logger.error("Logback configuration file not found.", e);
				try {
					resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
					file = ResourceUtils.getFile(resolvedLocation);
				} catch (FileNotFoundException fileNotFoundExceptionAbsolut) {
					LogbackConfigurer.logger.error(
							"There has been an error of incorrect path. The route is not included in the application classpath or an absolute path is correct.",
							fileNotFoundExceptionAbsolut);
				}
			}
			LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
			try {
				JoranConfigurator configurator = new JoranConfigurator();
				configurator.setContext(lc);
				lc.reset();
				configurator.doConfigure(file);
			} catch (JoranException je) {
				LogbackConfigurer.logger.error("Logback configure error.", je);
				throw new FileNotFoundException(
						"There was an error initializing the system logs (logback). The specified file is incorrect or corrupt. "
								+ je.getMessage());
			}
			if (printState) {
				lc.getStatusManager();
			}
		} else {
			throw new FileNotFoundException("The file specified for logback settings should be an xml file.");
		}
	}
}
