#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

import sys
import traceback
import gtk

from winswitch.util.simple_logger import Logger

logger=Logger("error_handling", log_colour=Logger.RED)


def formatExceptionInfo(maxTBlevel=5):
	cla, exc, trbk = sys.exc_info()
	excName = cla.__name__
	try:
		excArgs = exc.__dict__["args"]
	except KeyError:
		excArgs = "<no args>"
	excTb = traceback.format_tb(trbk, maxTBlevel)
	return (excName, excArgs, excTb)

def get_error_messages():
	error=formatExceptionInfo()
	try:
		excPattern = (error[0], error[1])
		return repr(excPattern)
	except KeyError:
		return error
	except:
		return error    # maybe was not tuple?

def get_error_message():
	errs=get_error_messages()
	error=""
	for err in errs:
		error="%s\n%s" % (error,err)
	return	error;

def display_exception(title):
	message=get_error_message()
	display_error(title,message)

def display_error(title,message=None):
	logger.log("(%s,%s)" % (title,message))
	text_message = title
	if message:
		text_message += "\n" + str(message)
	dia = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, text_message)
	dia.set_title(title)
	dia.show_all()
	dia.run()
	dia.destroy()
	logger.debug("(%s,%s) done" % (title,message))
