import logging
import os
import psycopg2
import yaml

log: logging.Logger = logging.getLogger('development')


class _DBConnection:
    """
    Utility DAO to handle DB Connection using Singleton pattern.
    Connection will autoclose upon termination of program, or deletion of instance.
    """
    instance = None
    con = None

    def __new__(cls):
        if _DBConnection.instance is None:
            _DBConnection.instance: _DBConnection = object.__new__(cls)
        return _DBConnection.instance

    def __init__(self) -> None:
        if _DBConnection.con is None:
            try:
                with open(os.path.join(os.getcwd(),
                                       "configs/db_conn.yaml")) as yaml_conf:
                    conf = yaml.safe_load(yaml_conf)
                _DBConnection.con: psycopg2.connection = psycopg2.connect(
                    host=conf['Postgres']['url'],
                    port=conf['Postgres']['port'],
                    database=conf['Postgres']['database'],
                    user=conf['Postgres']['user'],
                    password=conf['Postgres']['password'])
            except psycopg2.DatabaseError as db_error:
                log.error(f"{db_error}")
            else:
                log.info("Postgres connection established")

    def __del__(self) -> None:
        if _DBConnection.con is not None:
            _DBConnection.con.close()
            log.info('Database connection closed.')
