#!/usr/bin/env python3

# A bottle plugin for send emails if error

from settings import config
from cuchulu.libraries.sendmail import SendMail
import sys, traceback

email_failed=''

if hasattr(config, 'email_failed'):
    email_failed=config.email_failed

class ErrorReportingPlugin(object):
    """Bottle plugin for send email if exception
    
    A simple plugin that send an email to email_failed config variable with email address.
    
    """

    name = 'error_reporting'
    api = 2

    def apply(self, callback, context):
        
        def wrapper(*args, **kwargs):
        
            try:
            
                rv = callback(*args, **kwargs)

                return rv
                
            except Exception as exception:
                #print('detected error')
                
                # Send mail with error. 
                
                if email_failed!='' and type(exception).__name__!='HTTPResponse':

                    sendmail=SendMail()

                    text=traceback.format_exc()

                    sendmail.send(email_failed, [email_failed], 'Error reporting from site', text, content_type='plain', attachments=[])

                raise
                #return rv
                    
        return wrapper
