import pathlib

import tomlkit


def default_path(filename='config.toml'):
    path = pathlib.Path().home().joinpath('.config', 'mucus')
    if filename is not None:
        path = path.joinpath(filename)
    return path


def load(path: pathlib.Path = None) -> tomlkit.TOMLDocument:
    if path is None:
        path = default_path()
    try:
        with path.open('r') as f:
            doc = tomlkit.load(f)
    except FileNotFoundError:
        doc = tomlkit.document()
    doc.add('path', str(path))
    return doc


def dump(config: tomlkit.TOMLDocument, path: pathlib.Path = None):
    if path is None:
        try:
            path = pathlib.Path(config['path'])
        except KeyError:
            path = default_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    config.remove('path')
    with path.open('w') as f:
        tomlkit.dump(config, f)
