import pathlib

import tomlkit


def default_path(filename='data.toml'):
    return pathlib.Path().home().joinpath('.local', 'share', 'mucus', filename)


def dump(doc: tomlkit.TOMLDocument, path: pathlib.Path = None):
    if path is None:
        try:
            path = pathlib.Path(doc['path'])
        except KeyError:
            path = default_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    doc.remove('path')
    with path.open('w') as f:
        tomlkit.dump(doc, f)
    doc['path'] = str(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['path'] = str(path)
    return doc


def get(key, path: pathlib.Path = None):
    return load(path).get(key)


def set(key, value, path: pathlib.Path = None):
    doc = load(path)
    doc[key] = value
    dump(doc, path)


def hget(name, key, path: pathlib.Path = None):
    try:
        return load(path)[name][key]
    except KeyError:
        return None


def hset(name, key, value, path: pathlib.Path = None):
    doc = load(path)
    try:
        doc[name]
    except KeyError:
        doc[name] = {}
    doc[name][key] = value
    dump(doc, path)
