package com.ejie.ad74a.exceptions;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;

import com.ejie.ad74a.util.comun.Utilidades;
import com.ejie.ad74a.util.constantes.Constantes;

public class ManagerErrors {

	private static final Logger logger = LoggerFactory.getLogger(ManagerErrors.class);

	public static void manageError(String msg) {
		manageException(null, msg);
	}

	public static void manageException(Throwable throwable) {
		manageException(throwable, null, null);
	}

	public static void manageException(Throwable throwable, String msg) {
		manageException(throwable, msg, null, null);
	}

	public static void manageException(Throwable throwable, String msg, String msgToConsole,
			Map<String, String> infoMap) {
		manageException(throwable, msg, msgToConsole, null, infoMap);
	}

	public static void manageException(Throwable throwable, String msg, String msgToConsole, String codeError,
			Map<String, String> infoMap) {
		manageException(throwable, msg, msgToConsole, codeError, infoMap, false);
	}

	public static void manageException(Throwable throwable, String msg, String msgToConsole) {
		manageException(throwable, msg, msgToConsole, null);
	}

	public static void manageException(Throwable throwable, String msg, String msgToConsole, String codeError,
			Map<String, String> infoMap, boolean withStackTrace) {

		if (throwable != null) {
			logger.error("ERROR: " + throwable.getMessage(), throwable);
			if (throwable instanceof Ad74aException) {
				throw (Ad74aException) throwable;
			}
		}

		if (msg == null || (msg != null && msg.trim().length() == 0)) {
			msg = "En estos momentos no es posible realizar su petición";
		} else {
			try {
				String texto = Utilidades.getLabelFromResource(Constantes.BASENAME_RESOURCE_AD74A_I18N, msg,
						LocaleContextHolder.getLocale());
				logger.error("ERROR VALIDACION: " + texto);
				if (!Utilidades.esBlancoNulo(texto)) {
					msg = texto;
				}
			} catch (Exception e) {

			}
		}

		Ad74aException ad74aException = null;
		if (throwable != null) {
			ad74aException = new Ad74aException(throwable, msg);
		} else {
			ad74aException = new Ad74aException(msg);
		}

		if (withStackTrace) {
			StringWriter stackSw = new StringWriter();
			throwable.printStackTrace(new PrintWriter(stackSw));
		}
		if (msgToConsole != null) {
			ad74aException.setMsgToConsole(msgToConsole);
		}
		if (codeError != null) {
			ad74aException.setCodeError(codeError);
		}
		if (infoMap != null && infoMap.size() > 0) {
			ad74aException.setInfoMap(infoMap);
		}
		throw ad74aException;
	}

	public static void manageExceptionNoException(Throwable throwable, String msg) {
		manageException(throwable, null, null);
	}

}
