import logging
import os.path
import sys
from configparser import BasicInterpolation, ConfigParser



class EnvInterpolation(BasicInterpolation):
    """
    Interpolation which expands environment variables in values.
    """

    def before_get(self, parser, section, option, value, defaults):
        value = super().before_get(parser, section, option, value, defaults)

        if not os.path.expandvars(value).startswith('$'):
            return os.path.expandvars(value)
        else:
            return


try:

    config = ConfigParser(interpolation=EnvInterpolation())
    config.read(f"conf/application.conf")
except Exception as e:

    sys.stdout.flush()
    sys.exit()


class Secrets:
    auth_username = config.get("SECRETS", "digest_user")
    auth_password = config.get("SECRETS", "digest_pw")

class Service:
    events_proxy = config['SERVICE']['events_proxy']

class RedisConfig:
    uri = config.get("REDIS", "uri")
    login_db = config.getint("REDIS", "login_db")
    project_tags_db = config.getint("REDIS", "project_tags_db")

class PathToStorage:
    BASE_PATH = config.get("DIRECTORY", "base_path")
    if not BASE_PATH:
        print("Error, environment variable BASE_PATH not set")
        sys.exit(1)
    MOUNT_DIR = config.get("DIRECTORY", "mount_dir")
    if not MOUNT_DIR:
        print("Error, environment variable MOUNT_DIR not set")
        sys.exit(1)
    MODULE_PATH = os.path.join(BASE_PATH, MOUNT_DIR)


class KeyPath:
    keys_path = config['DIRECTORY']['keys_path']
    public = os.path.join(PathToStorage.BASE_PATH, keys_path, "public")
    private = os.path.join(PathToStorage.BASE_PATH, keys_path, "private")
    if not os.path.isfile(public) or not os.path.isfile(private):
        logging.warning("Login Token Keys are not available! Authentication may fail!")