package de.hsadmin.cliClientConnector;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

import javax.persistence.RollbackException;

public class TechnicalException extends RuntimeException {
	
	private static final long serialVersionUID = 1L;

	public TechnicalException(Throwable e) {
		super(extractCauseMessage(e));
	}

	private static String extractCauseMessage(Throwable e) {
		if (e.getMessage() != null && !(e instanceof RollbackException)) {
			return e.getMessage();
		}
		else if (e instanceof InvocationTargetException || e instanceof RollbackException) {
			String sqlState = null;
			Throwable cause = e.getCause();
			Throwable prev = null;
			while (cause != null && cause != prev) {
				prev = cause;
				cause = prev.getCause();
				if ((cause == null || cause == prev)
						&& prev instanceof SQLException) {
					SQLException sqlExc = (SQLException) prev;
					sqlState = sqlExc.getSQLState();
					cause = sqlExc.getNextException();
				}
			}
			if (cause == null)
				cause = prev;
			if (cause != null)
				return composeMessage(sqlState, cause.getMessage());
			if (e instanceof InvocationTargetException) {
				return composeMessage(sqlState, ((InvocationTargetException) e).getTargetException().getMessage());
			}
		}
		return e.getClass() + " without detail message";
	}

	private static String composeMessage(String sqlState, String message) {
		if (sqlState != null) return "SQLSTATE[" + sqlState + "] " + message;
		return message;
	}

}
