
import logging, sqlalchemy
from common.Settings import get_setting

LOGGER = logging.getLogger(__name__)
CRDB_URI_TEMPLATE = 'cockroachdb://{:s}:{:s}@cockroachdb-public.{:s}.svc.cluster.local:{:s}/{:s}?sslmode={:s}'

class LSPEngine:
    @staticmethod
    def get_engine() -> sqlalchemy.engine.Engine:
        crdb_uri = get_setting('CRDB_URI', default=None)
        if crdb_uri is None:
            CRDB_NAMESPACE = get_setting('CRDB_NAMESPACE')
            CRDB_SQL_PORT  = get_setting('CRDB_SQL_PORT')
            CRDB_DATABASE_LSP_MGMT = 'tfs_lsp_mgmt'             # TODO: define variable get_setting('CRDB_DATABASE_KPI_MGMT')
            CRDB_USERNAME  = get_setting('CRDB_USERNAME')
            CRDB_PASSWORD  = get_setting('CRDB_PASSWORD')
            CRDB_SSLMODE   = get_setting('CRDB_SSLMODE')
            crdb_uri = CRDB_URI_TEMPLATE.format(
                CRDB_USERNAME, CRDB_PASSWORD, CRDB_NAMESPACE, CRDB_SQL_PORT, CRDB_DATABASE_LSP_MGMT, CRDB_SSLMODE)
        try:
            engine = sqlalchemy.create_engine(crdb_uri, echo=False)
            LOGGER.info(' LspDB initalized with DB URL: {:}'.format(crdb_uri))
        except: # pylint: disable=bare-except # pragma: no cover
            LOGGER.exception('Failed to connect to database: {:s}'.format(str(crdb_uri)))
            return None # type: ignore
        return engine