#######################################################################################
# Designed and Coded by Cal Leeming for Simplicity Media Ltd
# cal.leeming [at] simplicitymedialtd.co.uk
#######################################################################################

def ReportBug(request=None, serno=None):
    try:
        from webapp.de.djangologging import middleware
        from django.core.mail import mail_admins
        import sys
        import traceback
        import os

        # Mail the admins with the error
        exc_info = sys.exc_info()

        if exc_info:
            _file, _line, _func, _line = traceback.extract_tb(exc_info[2])[0]
            _file = os.path.basename(_file)

        else:
            _file, _line, _func, _line = (None, None, None, None)


        # Check if we have a serno
        if not serno:
            from hashlib import md5
            import random
            serno = md5()
            serno.update(str(random.random()))
            serno = serno.hexdigest()

        import sys
        from django.views.debug import ExceptionReporter
        from django.http import HttpRequest
        from django.conf import settings
        from django.core.mail import EmailMultiAlternatives
        if not request:
            h = HttpRequest()
            h.META['SERVER_NAME'] = 'FAKE'
            h.META['SERVER_PORT'] = '80'
        else:
            h = request
            
        exp = sys.exc_info()
        t = ExceptionReporter(h, *exp)

        if request:
            subject = "[Django] [%s] Exception: %s"%(request.META['REMOTE_ADDR'], str(exp[1]))
        else:
            subject = "[Django] Exception: %s"%(str(exp[1]))

        from_email = settings.SERVER_EMAIL
        to = map(lambda x: x[1], settings.ADMINS)

        text_content = 'Traceback:\n%s\n\n' % ('\n'.join(traceback.format_exception(*exc_info)),)
        html_content = t.get_traceback_html()
        msg = EmailMultiAlternatives(subject, text_content, from_email, to)
        msg.attach_alternative(html_content, "text/html")
        msg.send()
        print "Message sent"

        # Mail the admins with the error
        exc_info = sys.exc_info()
        subject = 'Uncaught exception'
        try:
            request_repr = repr(request)
        except:
            request_repr = 'Request repr() unavailable'
        import traceback
        message = 'Traceback:\n%s\n\nRequest:\n%s' % (
            '\n'.join(traceback.format_exception(*exc_info)),
            request_repr,
        )
        print "------------------- traceback -------------------"
        print message
        print "-------------------------------------------------"
        print ""
        print ""

    except Exception, e:
        try:
            # Mail the admins with the error
            exc_info = sys.exc_info()
            subject = 'Uncaught exception'
            try:
                request_repr = repr(request)
            except:
                request_repr = 'Request repr() unavailable'
            import traceback
            message = 'Traceback:\n%s\n\nRequest:\n%s' % (
                                                          '\n'.join(traceback.format_exception(*exc_info)),
                                                          request_repr,
                                                          )
            mail_admins(subject, message, fail_silently=True)

            print "------------------- traceback (oops) -------------------"
            print message
            print "--------------------------------------------------------"
            print ""
            print ""
            
        except Exception, e:
            mail_admins("SERIOUS ERROR", "Not sure what happened.. %s"%str(e), fail_silently=True)

# Example Usage
try:
    raise Exception, "test"
except Exception, e:
    ReportBug()