from pathlib import Path
import json


def get_if_not_exists(date, function, name, location='/tmp', *args):
    """Load file if it exists, else call a function to create it.

    Args:
        date (str): string identifier of file
        function (fct): function to call is file does not exist
        name (str): base name of file
        location (str, optional): path to file. Defaults to '/tmp'.

    Returns:
        json-serializeable object: result from generating or loading a json file
    """
    loc = Path(location) / '{}_{}'.format(date, name)
    output = None
    if loc.is_file():
        print("Loading {} from {}".format(name, str(loc)))
        with loc.open(mode='r') as j_in:
            output = json.load(j_in)
    else:
        output = function(*args)
        with loc.open(mode='w') as j_out:
            json.dump(output, j_out, indent=4)
        print("Saved {} to {}".format(name, str(loc)))
    return output