import json


def categorize_dimensions(data_files):
    """ Categorize dimensions as cprops, spatial dimensions or time dimensions
    Args:
        data_files: list of the raw data json files
    Returns:
        an object: {
            spatial: map of spatial dimensions to the number of occurences,
            time: list of time dimensions,
            cprop: sorted list of {id: dimension code as string,
                                   num: number of occurences}
        }
    """
    spatial_dim = {}
    time_dim = set()
    cprop_dim = {}
    for f in data_files:
        with open(f, "r+") as indicator_data:
            indicator_data = json.load(indicator_data).get("value", [])
        if len(indicator_data) == 0:
            continue
        for data in indicator_data:
            spatial_dim_type = data.get("SpatialDimType", "")
            spatial_dim_count = spatial_dim.get(spatial_dim_type, 0)
            spatial_dim[spatial_dim_type] = spatial_dim_count + 1
            time_dim.add(data.get("TimeDimType", ""))
            dim1Type = data.get("Dim1Type", "")
            if not dim1Type:
                continue
            dim1Count = cprop_dim.get(dim1Type, 0)
            cprop_dim[dim1Type] = dim1Count + 1
            dim2Type = data.get("Dim2Type", "")
            if not dim2Type:
                continue
            dim2Count = cprop_dim.get(dim2Type, 0)
            cprop_dim[dim2Type] = dim2Count + 1
            dim3Type = data.get("Dim3Type", "")
            if not dim3Type:
                continue
            dim3Count = cprop_dim.get(dim3Type, 0)
            cprop_dim[dim3Type] = dim3Count + 1
    cprop_list = []
    for prop in cprop_dim:
        cprop_list.append({"id": prop, "num": cprop_dim.get(prop)})
    sorted_cprop_list = sorted(cprop_list,
                               key=lambda x: x.get("num"),
                               reverse=True)
    result = {
        "spatial": spatial_dim,
        "time": list(time_dim),
        "cprop": sorted_cprop_list
    }
    return result