from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

DATABASE_BD = "CHANGE_ME"
DRIVER_ODBC = "CHANGE_ME"
PASSWORD_BD = "CHANGE_ME"
SERVER_BD = "CHANGE_ME"
USER_BD = "CHANGE_ME"


class DBConnectionHandler:

    def __init__(self) -> None:
        self.__connection_string = (
            f"DRIVER={{ODBC Driver {DRIVER_ODBC} for SQL Server}};"
            f"SERVER={SERVER_BD};"
            f"DATABASE={DATABASE_BD};"
            f"UID={USER_BD};"
            f"PWD={PASSWORD_BD};"
        )
        self.__engine = self.__create_database_engine()
        self.session = None

    def __create_database_engine(self):
        engine = create_engine(
            f"mssql+pyodbc:///?odbc_connect={self.__connection_string}"
        )
        return engine

    def get_engine(self):
        return self.__engine

    def __enter__(self):
        session_maker = sessionmaker(bind=self.__engine)
        self.session = session_maker()

        return self

    def __exit__(self, exc_tupe, exc_val, exc_tb):
        self.session.close()  # type: ignore
        self.get_engine().dispose()
