import yaml
import sys
from functools  import reduce

def load_yaml_config(path: str):
        with open(path) as f:
            config = yaml.safe_load(f)
        return config

def dumdict2yaml(data_dict,file):
    yaml.dump(data_dict,file)

def getFunctionFromModules(sysModules):
    def getFunction(functionName):
        if isinstance(functionName,str):
            if functionName[0]=='$':
                get_class = lambda name: reduce(getattr, name.split('.')[1:], __import__(name.partition('.')[0]))
                
                if '.' in functionName:
                    return get_class(functionName[1:]) #type_to_function[functionName]
                else:
                    return getattr(sysModules, functionName[1:]) #getattr(functionName[1:])
        return functionName
    return getFunction


def getParams(subconfig: dict, paramName: str,toParamFunction=None):
    assert (paramName in subconfig.keys())
    confParam=subconfig[paramName]
    if confParam is None:
        return {}
    if toParamFunction is None:
        return subconfig[paramName]
    else:
        dict_params = {}    
        for k in confParam.keys():
            dict_params[k]=toParamFunction(confParam[k])
        return dict_params


