from messageprocessor import MessageProcessorCallback


class DbApiTransactionCallback(MessageProcessorCallback):

    def __init__(self):
        self.conn = None

    def update_conn(self, conn):
        self.conn = conn

    def process_begun(self, event_name, request_id, data):
        return

    def input_parsed(self, event_name, request_id, input_obj):
        return

    def business_called(self, event_name, request_id, input_obj, output_obj):
        if self.conn:
            self.conn.commit()

    def process_finished(self, event_name, request_id, input_obj, output_obj):
        return

    def parse_exception(self, event_name, request_id, data, exception):
        self._rollback()

    def unhandled_exception(self, event_name, request_id, input_obj, exception):
        self._rollback()

    def _rollback(self):
        if self.conn:
            self.conn.rollback()
