from pathlib import Path

from risc_lasagna.layer.dict_layer import DictLayer
from risc_lasagna.typedef import ConfigurationError


class _DotEnvLayer(DictLayer):
    pass


def DotEnvLayer(
    file: Path,
    raise_exception_if_file_not_readable: bool = False,
    comment_char: str = "#",
    capitalize_keys: bool = True,
    variable_prefix: str = "",
) -> _DotEnvLayer:
    """
    Reads a .env files and parses it into an environment layer. Example .env
    EFRE_RESINET_A=123456789
    EFRE_RESINET_B=123456789

    Creates the DotEnv Layer from a given file
    :param file: Path to file
    :param raise_exception_if_file_not_readable: If the layer should raise an exception if file can not be read
    or act as an 'empty' layer
    :param comment_char: First non whitespace char which marks the line as a comment (will be ignored)
    :param capitalize_keys: If keys should automatically be capitalized -> makes everything case insensitive. (makes
    sense in some environments)
    :param variable_prefix: Prefix which is prepended before every key
    """
    map_ = {}
    try:
        with open(file, "r") as f:
            # open and parse the file, ignore comment lines (starting with comment char)
            for line in f.readlines():
                if not line.strip().startswith(comment_char):
                    line = tuple(line.split("="))
                    # skip empty lines or comments
                    if len(line) != 2:
                        continue
                    # add new keys to the map
                    map_[line[0].strip()] = line[1].strip()
    except (IOError, OSError) as e:
        if raise_exception_if_file_not_readable:
            raise ConfigurationError from e

    return _DotEnvLayer(
        map_, variable_prefix=variable_prefix, capitalize_keys=capitalize_keys
    )
