#!/usr/bin/env python3

# A bottle plugin for send emails if 

from settings import config
from paramecio.citoplasma.sendmail import SendMail
import sys, traceback

email_failed=''

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

class ErrorReportingPlugin(object):

    name = 'error_reporting'
    api = 2

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

                return rv
                
            except:
                
                #print('detected error')
                
                # Send mail with error. 
                
                if email_failed!='':

                    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
