import logging
from enum import Enum
from common.Settings import get_setting
from common.database.api.Database import Database
from common.database.engines.inmemory.InMemoryDatabaseEngine import InMemoryDatabaseEngine
from common.database.engines.redis.RedisDatabaseEngine import RedisDatabaseEngine

LOGGER = logging.getLogger(__name__)

class DatabaseEngineEnum(Enum):
    INMEMORY = 'inmemory'
    REDIS = 'redis'
    #MONGO = 'mongo'
    #RETHINK = 'rethink'
    #ETCD = 'etcd'

ENGINES = {
    DatabaseEngineEnum.INMEMORY.value: InMemoryDatabaseEngine,
    DatabaseEngineEnum.REDIS.value: RedisDatabaseEngine,
    #DatabaseEngineEnum.MONGO.value: MongoDatabase,
    #DatabaseEngineEnum.RETHINK.value: RethinkDatabase,
    #DatabaseEngineEnum.ETCD.value: EtcdDatabase,
}

DEFAULT_DB_ENGINE = DatabaseEngineEnum.INMEMORY

def get_database(engine=None, **settings) -> Database:
    # return an instance of Database initialized with selected engine.
    # Engine is selected using following criteria (first that is not None is selected):
    # 1. user selected by parameter (engine=...)
    # 2. environment variable DB_ENGINE
    # 3. default engine: INMEMORY
    if engine is None: engine = get_setting('DB_ENGINE', default=DEFAULT_DB_ENGINE)
    if engine is None: raise Exception('Database Engine not specified')
    if isinstance(engine, DatabaseEngineEnum): engine = engine.value
    engine_class = ENGINES.get(engine)
    if engine_class is None: raise Exception('Unsupported DatabaseEngine({})'.format(engine))
    LOGGER.info('Selected Database Engine: {}'.format(engine))
    return Database(engine_class(**settings))
