# AUTOGENERATED! DO NOT EDIT! File to edit: config.ipynb (unless otherwise specified).

__all__ = ['__jedi_toolz_var__', '__jedi_toolz_path__', '__jedi_toolz_path_method__', 'set_path', 'as_dict',
           'as_records', 'select', 'example_ini']

# Cell
from configparser import ConfigParser
import os
from pathlib import Path

__jedi_toolz_var__ = "JEDI_TOOLZ_PATH"
__jedi_toolz_path__ = ""
__jedi_toolz_path_method__ = ""

# Cell
def set_path(config_path=None) -> Path:
    global __jedi_toolz_path__
    global __jedi_toolz_path_method__

    # Set __jedi_toolz_path__
    if config_path:
        __jedi_toolz_path_method__ = "config_path"
        __jedi_toolz_path__ = config_path
    elif __jedi_toolz_path__:
        pass #already set
    else:
        var = os.get_env(__jedi_toolz_var__)
        __jedi_toolz_path_method__ = __env_var__
        __jedi_toolz_path__ = var

    # config_path AND __jedi_toolz_var__ don't exist
    assert __jedi_toolz_path__ is not None, f"config_path or {__jedi_toolz_var} not provided"
    path = Path(__jedi_toolz_path__).expanduser()
    assert path.exists(), f"{__jedi_toolz_path__} does not exist"
    return path

# Cell
def as_dict():
    """Returns configurations as a nested dict. Keys and values are strings."""
    location = set_path()
    cfg = ConfigParser()
    cfg.read(location)
    sections = cfg.sections()
    result = {}
    for section in sections:
        options = {k: v for k, v in cfg[section].items()}
        result[section] = options
    return result

# Cell
def as_records():
    """Returns configurations as a list of dicts."""
    return [
        {"section": section, "option": option, "value": value}
        for section, options in as_dict().items()
        for option, value in options.items()
    ]

# Cell
def select(section, option=None):
    """Returns the configuration a nested dict or value."""
    settings = as_dict()
    if option:
        return settings[section][option]
    else:
        return settings[section]

# Cell
def example_ini():
    path = Path.cwd() / "example.ini"
    with path.open(mode="w") as file:
        file.writelines([
            "[test1]\n",
            "value1 = 5\n",
            "value2 = 6\n",
            "\n",
            "[test2]\n",
            "valuea = ABC\n",
            "valueb = 123\n",
        ])
    return path