import yaml


def gen_lookup(file):
    """ Generating the lookup table between api-endpoints and elasticsearch
        instances from the configuration of the lod-api.

        lookup table is of the form:
            {"/api/endpoint": "http://elasticsearchhost:port/index/doctype",
             "/resource": "http://elasticsearchhost:9200/resource/data",
             "/works": …,
            }
        returns: dict.
    """
    es_lookup = dict()

    # read complete api configuration
    with open(file, 'r') as instream:
        config = yaml.safe_load(instream)

    # generate lookup for source indices
    for source, instance in config["source_indices"].items():
        key = "/source/{}".format(source)
        # remove trailing slash from index-URL
        es_lookup[key] = instance.rstrip("/")

    # generate remaining index lookups
    es_address = "http://{h}:{p}".format(h=config["es_host"],
                                          p=config["es_port"])
    for ctx in config["indices"]:
        doctype = config["indices"][ctx].get("type")
        index = config["indices"][ctx].get("index")
        es_lookup["/" + index] = "{h}/{i}/{t}".format(
                h=es_address, i=index, t=doctype)

    return es_lookup