
from sqlalchemy import create_engine


from hawkSoar.common.logger import get_logger


class DBInterface(object):
    """
    This is the Sqlite interface base class handling loading config and setup connections
    """

    def __init__(self, config=None):
        self.engines = {
            'sqlite': 'sqlite:///{DB}',
            'mysql': 'mysql://{USER}:{PASSWORD}@{HOST}/{DB}'
        }

        self.logger = get_logger()

        self.config = config
        self.client = self._connect()
        self._authenticate()
        self._setup_database_mapping()

    def _connect(self):
        db_engine = None
        if self.config['DB_TYPE'] == 'sqlite':
            engine_url = self.engines[self.config['DB_TYPE']].format(
                DB=self.config['DB_NAME'])
            db_engine = create_engine(engine_url)

        elif self.config['DB_TYPE'] == 'mysql':
            engine_url = self.engines[self.config['DB_TYPE']].format(USER=self.config['USERNAME'],
                                                                     PASSWORD=self.config['PASSWORD'],
                                                                     HOST=self.config['HOST'],
                                                                     DB=self.config['DB_NAME'])
            db_engine = create_engine(engine_url)

        else:
            self.logger.error('DB_TYPE %s is not found in DB_ENGINE: %s' % (
                self.config['DB_TYPE'], db_engine))

        self.logger.info('Database interface opened for: %s %s' %
                         (self.config['DB_TYPE'], db_engine))
        return db_engine

    def shutdown(self):
        # close doesnt exist
        if self.client:
            self.client.dispose()

    def _setup_database_mapping(self):
        pass

    def _authenticate(self):
        pass
