# coding: utf-8

from os import environ as sysenv
from typing import Optional, Any

from .error import Error
from ._lib import _UNDEFINED


class EnvConfigError(Error):
    def __init__(self, param_name: str, message: Any):
        super().__init__(f'Ошибка в параметре: {param_name} - {message}')


def get_env(name: str, type_name: type, default: Optional[Any] = _UNDEFINED, mandatory: bool = False):
    try:
        return type_name(sysenv[name])

    except (ValueError, TypeError) as e:
        raise EnvConfigError(name, f'Ошибка преобразования типа - {e}')

    except KeyError:
        if default is not _UNDEFINED:
            return default

        elif mandatory:
            raise EnvConfigError(name, 'Не установлен параметр')

        else:
            return None
