"""
Database configuration functions.

Main class is DBConfig, which encapsulates a database configuration
passed in as a file or object. For example::

    cfg1 = DBConfig()  # use defaults
    cfg2 = DBConfig("/path/to/myfile.json")  # read from file
    f = open("/other/file.json")
    cfg3 = DBConfig(f)  # read from file object
    # access dict of parsed conf. settings
    settings = cfg1.settings

"""
__author__ = "Dan Gunter <dkgunter@lbl.gov>"
__date__ = "4/25/14"

import os
import ruamel.yaml as yaml

# Constants for keys
HOST_KEY = "host"
PORT_KEY = "port"
DB_KEY = "database"
COLL_KEY = "collection"
USER_KEY = "user"
PASS_KEY = "password"
ALIASES_KEY = "aliases"


class ConfigurationFileError(Exception):
    def __init__(self, filename, err):
        msg = f"reading '{filename}': {err}"
        Exception.__init__(self, msg)


class DBConfig:
    """Database configuration."""

    DEFAULT_PORT = 27017
    DEFAULT_FILE = "db.json"
    ALL_SETTINGS = [
        HOST_KEY,
        PORT_KEY,
        DB_KEY,
        COLL_KEY,
        ALIASES_KEY,
    ]
    DEFAULT_SETTINGS = [
        (HOST_KEY, "localhost"),
        (PORT_KEY, DEFAULT_PORT),
        (DB_KEY, "vasp"),
        (ALIASES_KEY, {}),
    ]

    def __init__(self, config_file=None, config_dict=None):
        """
        Constructor.

        Settings are created from config_dict, if given,
        or parsed config_file, if given, otherwise
        the DEFAULT_FILE is tried and if that is not present