# -*- coding: utf-8 -*-
import os
from pathlib import Path
from typing import Any, Mapping, Optional, Type

from eduid_common.config.base import TBaseConfigSubclass
from eduid_common.config.parsers.base import BaseConfigParser

__author__ = 'ft'

from eduid_common.config.parsers.exceptions import ParserException


def load_config(
    typ: Type[TBaseConfigSubclass], ns: str, app_name: str, test_config: Optional[Mapping[str, Any]] = None,
) -> TBaseConfigSubclass:
    """ Figure out where to load configuration from, and do it. """
    parser = _choose_parser(app_name, ns)

    if not parser:
        raise ParserException('Could not find a suitable config parser')

    if test_config:
        return typ(**test_config)

    config = parser.read_configuration()

    return typ(**config)


def _choose_parser(app_name: str, ns: str) -> Optional[BaseConfigParser]:
    parser: Optional[BaseConfigParser] = None
    ns = os.environ.get('EDUID_CONFIG_NS', ns)
    app_name = os.environ.get('EDUID_CONFIG_APP_NAME', app_name)
    yaml_file = os.environ.get('EDUID_CONFIG_YAML')
    if yaml_file:
        try:
            # Do not force applications that does not use EtcdConfigParser to have yaml and etcd installed
            from eduid_common.config.parsers.yaml import YamlConfigParser

            parser = YamlConfigParser(path=Path(yaml_file), ns=ns, app_name=app_name)
        except ImportError:
            raise ParserException('YamlConfigParser could not be imported')
    if not parser:
        try:
            # Do not force applications that does not use EtcdConfigParser to have yaml and etcd installed
            from eduid_common.config.parsers.etcd import EtcdConfigParser
        except ImportError:
            raise ParserException('EtcdConfigParser could not be imported')

        parser = EtcdConfigParser(namespace=f'/{ns}/{app_name}')
    return parser

@@ -863,16 +863,321 @@
 arser%5D:%0A
+    %22%22%22%0A    Choose a parser to use for this app.%0A%0A    Do local imports accordingly to not make etcd, yaml etc. mandatory requirements for%0A    all users of eduid-common.%0A%0A    :param app_name: Name of the application%0A    :param ns: Namespace for the application%0A%0A    :return: Config parser instance%0A    %22%22%22%0A
     pars
@@ -1214,16 +1214,16 @@
  = None%0A
-
     ns =
@@ -1413,115 +1413,8 @@
 ry:%0A
-            # Do not force applications that does not use EtcdConfigParser to have yaml and etcd installed%0A
     
@@ -1685,32 +1685,32 @@
  if not parser:%0A
+
         try:%0A   
@@ -1710,115 +1710,8 @@
 ry:%0A
-            # Do not force applications that does not use EtcdConfigParser to have yaml and etcd installed%0A
     

improve documentation