import json


def get_sdsandbox_json_steer_angle(fpath):
    """
    Get steering angle stored in json file.
    The argument passed in the path for a file, that was stored with a corresponding json file 
    containing a steering angle, looks something like:
    C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\ \
    12893_cam-image_array_.jpg
    The json file with with steering angle, in the same path, will be named record_12893.json
    We open that file and return the steering angle.
    
    Parameters
    -------   
        fpath: string, filepath
    
    Returns
    -------  
        st_angle: steering angle
    
    Example
    ------- 
    fpath = 'C:\\Users\\aczd097\\Downloads\\dataset\\unity\\log_sample\\logs_Mon_Jul_13_08_29_01_2020\\12893_cam-image_array_.jpg'
    jsa = get_sdsandbox_json_steer_angle(fpath)
    print(jsa)
    """ 
    
    # split string
    fsplit = fpath.split('\\')
    # get name e.g. 12893_cam-image_array_.jpg
    fname = fsplit[-1]
    # get number e.g. 12893
    fnumber = fsplit[-1].split('_')
    fnumber = fnumber[0]
    # build json file name e.g. record_12893.json
    fname = 'record_' + fnumber + '.json'
    # build file path e.g. 'C:\Users\aczd097\Downloads\dataset\unity\log_sample\logs_Mon_Jul_13_08_29_01_2020\record_12893.json'
    idx = fpath.rindex('\\') + 1
    fname = fpath[0:idx] + fname
    # open and read file
    f = open(fname, "r")
    file = f.read()
    # load json
    fjson = json.loads(file)
    # get and return steering angle attribute
    st_angle = fjson['user/angle']
    return st_angle