"""
provides functions for reading login detail from .gel_config file
"""
import json
import os

def get_profile(f=os.path.expanduser(".gel_config"), items=None):
    """
    Get GEL profile details from file. See https://cnfl.extge.co.uk/pages/viewpage.action?pageId=113196964
    for details
    :params f: location of config file, default is .gel_config
    :params items: str or list of first-level items to return
    :returns: dictionary of gel_config items
    """

    # get file contents
    with open(f) as json_file:
        d = json.load(json_file)

    # filter out the items from the object (including .defaults)
    if items is not None:
        if type(items) is str:
            items = [items]
        d = {k: v for k, v in d.items() if k in items or k == '.defaults'}

    # do the default replacement
    replace_defaults(d)

    # if only asked for a single item, just give that, otherwise return the
    # whole dict
    if items is not None and len(items) == 1:
        return d[items[0]]
    else:
        return d


def recursive_search_replace(x, s, r):
    """
    Function to recursively search and replace within a dictionary
    :params x: dictionary containing items to be searched
    :params s: dictionary value to be replaced
    :params r: replacement for s
    :returns: dictionary with replacements
    """

    # go through each of the items in the dictionary
    for k, v in x.items():

        # if value is a dictionary do search replace on that
        if type(v) is dict:
            recursive_search_replace(v, s, r)

        # otherwise if the value matches the search string
        # replace it with replacement
        else:
            if v == s:
                x[k] = r


def replace_defaults(d):
    """
    Search and replace defaults in config dictionary, removes defaults section
    in the process. Replacements and removals are done in place
    :params d: dictionary object
    """

    # remove the defaults section
    defaults = d.pop('.defaults')

    # look for default tags and replace them
    for k, v in defaults.items():
        recursive_search_replace(d, '!' + k + '!', v)
