/**
 * UncaughtExceptionHandler.java
 * @date Jan 6, 2011
 * @author ricky barrette
 * @author Twenty Codes, LLC
 */
package com.TwentyCodes.java.OrderProcessor;

import com.TwentyCodes.java.OrderProcessor.UI.ExceptionReportGUI;

/**
 * An exception handler used to help report bugs in our applications 
 * @author ricky barrette
 */
public class UncaughtExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
	
	private java.lang.Thread.UncaughtExceptionHandler mDefaultUEH;
	
	@SuppressWarnings("rawtypes")
	private Class mApp;

	/**
	 * Creates a new UncaughtExceptionHandler
	 * @param c
	 * @author ricky barrette
	 */
	@SuppressWarnings("rawtypes")
	public UncaughtExceptionHandler(Class c) {
		mApp = c;
		mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler();
	 }

	/**
	 * (non-Javadoc)
	 * @see java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.lang.Thread, java.lang.Throwable)
	 * @author ricky barrette
	 */
	@Override
	public void uncaughtException(Thread t, Throwable e) {
		new ExceptionReportGUI(getDebugReport(e));
		mDefaultUEH.uncaughtException(t,e);
	}

	/**
	 * generates a human readable report about the exception
	 * @param e
	 * @return
	 * @author ricky barrette
	 */
	private String getDebugReport(Throwable e) {
		
		StackTraceElement[] theStackTrace = e.getStackTrace();
		
		StringBuffer report = new StringBuffer();
		
		report.append("We're sorry, but there was an error with your application.\n" +
				" Please email this report to twentycodes@gmail.com to help make this application better. \n\n");
		
		report.append("--------- Application ---------\n\n");
		
		report.append(mApp.getPackage());
		
		report.append(" generated the following exception:\n\n");
		
		report.append(e.toString() + "\n\n");
		
		report.append("-------------------------------\n\n");
		
		report.append("--------- Stack trace ---------\n\n");
		for (int i = 0; i < theStackTrace.length; i++) {
			report.append("    " + theStackTrace[i].toString() + "\n");
		}
		report.append("-------------------------------\n\n");
		
		// If the exception was thrown in a background thread inside
		// AsyncTask, then the actual exception can be found with getCause
		report.append("--------- Cause ---------------\n\n");
		Throwable cause = e.getCause();
		if (cause != null) {
			report.append(cause.toString() + "\n\n");
			theStackTrace = cause.getStackTrace();
			for (int i = 0; i < theStackTrace.length; i++) {
				report.append("    " + theStackTrace[i].toString() + "\n");
			}
		}
		report.append("-------------------------------\n\n");
		
		return report.toString();
	}

}