from sqlite3 import Connection
from typing import Any

from messageprocessor import MessageProcessorCallback


class SqliteConnectionTransactionCallback(MessageProcessorCallback):

    def __init__(
        self,
        conn: Connection,
    ) -> None:

        self.conn = conn

    def process_begun(
        self,
        event_name: str,
        request_id: str,
        **kwargs
    ) -> None:

        return

    def input_parsed(
        self,
        event_name: str,
        request_id: str,
        input_obj: Any,
    ) -> None:

        return

    def business_called(
        self,
        event_name: str,
        request_id: str,
        input_obj: Any,
        output_obj: Any,
    ) -> None:

        if self.conn.total_changes > 0:
            self.conn.commit()

    def process_finished(
        self,
        event_name: str,
        request_id: str,
        input_obj: Any,
        output_obj: Any,
    ) -> None:

        return

    def parse_exception(
        self,
        event_name: str,
        request_id: str,
        data: bytes,
        exception: Exception,
    ) -> None:

        return

    def unhandled_exception(
        self,
        event_name: str,
        request_id: str,
        input_obj: Any,
        exception: Exception,
    ) -> None:

        if self.conn.total_changes > 0:
            self.conn.commit()
        else:
            self.conn.rollback()
