from typing import Dict, Any

from app.main.engine.database.Mysql import Mysql

from app.main.engine.enum.DatabaseTypeEnum import DatabaseTypeEnum
import logging

logger = logging.getLogger()


class Database:

    def __init__(self, app, db_params: Dict[str, Any]) -> None:
        self.app = app
        self.db_type = db_params["type"]
        if self.db_type == DatabaseTypeEnum.MYSQL.value:
            host, port, user, password, database, params = (db_params["host"], db_params["port"], db_params["user"],
                                                            db_params["password"], db_params["db"], db_params["extra_params"])
            self.factory = Mysql(app, host, port, user, password, database, params)
        self.engine = None

    def create_spark_connection(self):
        jdbc_conn = None
        try:
            jdbc_conn = self.factory.create_spark_connection()
        except Exception as e:
            self.app.logger.error(f"Error creando spark conexión. {e}")
        finally:
            return jdbc_conn

    def get_basic_connection(self):
        connection = None
        try:
            connection = self.factory.get_basic_connection()
        except Exception as e:
            self.app.logger.error(f"Error trayendo básica conexión. {e}")
        finally:
            return connection

    def close_basic_connection(self) -> None:
        try:
            self.factory.connection.close()
            self.factory.connection = None
        except Exception as e:
            self.app.logger.error(f"Error cerrando básica conexión. {e}")

    def create_engine(self) -> None:
        try:
            if isinstance(self.engine, type(None)):
                self.factory.create_engine()
                self.engine = self.factory.engine
        except Exception as e:
            self.app.logger.error(f"Error creando db engine. {e}")

    def get_session(self):
        session = None
        try:
            session = self.factory.get_session()
        except Exception as e:
            self.app.logger.error(f"Error obteniendo sesion de conexion. {e}")
        finally:
            return session

    def verify_table(self, table_name, connection) -> bool:
        result = False
        try:
            result = self.factory.verify_table(table_name, connection)
        except Exception as e:
            self.app.logger.error(f"Error obteniendo numero de registros de la tabla. {e}")
        finally:
            return result

    def get_action_by_identifier(self, identifier, Session) -> str:
        script_name = None
        session = Session()
        try:
            self.create_engine()
            script_name = self.factory.get_action_by_identifier(identifier, session)
        except Exception as e:
            self.app.logger.error(f"Error obteniendo el nombre de la tabla según identificador. {e}")
        finally:
            session.close()
            return script_name
