import json
import sys
import os.path
import glob

def find_labeled_cell(layer_id, contour_id, feud_json, default=None):
    for layer in feud_json['layers']:
        cell_layer = layer['id']
        for cell in layer['contours']:
            if cell_layer == layer_id and cell['id'] == contour['id']:
                return cell['label']
    return default

dirname = os.path.normpath(sys.argv[1])
with open("{}/feud.json".format(dirname)) as feud_file:
    feud_json = json.load(feud_file)

print('\t'.join(("layer_id",
                 "contour_id",
                 "cell_label",
                 "centroid_x",
                 "centroid_y",
                 "r_avg",
                 "g_avg",
                 "b_avg",
                 "r_std",
                 "g_std",
                 "b_std" )))

for json_fn in glob.glob("{}/[0-9]*.json".format(dirname)):
    with open(json_fn) as json_file:
        layer_json = json.load(json_file)
    layer_id = layer_json['id']
    for contour in layer_json['contours']:
        contour_id = contour['id']
        cell_label = find_labeled_cell(layer_id, contour_id, feud_json)
        if not cell_label: continue
        centroid = contour['centroid']
        r_avg = contour['color_avg']["r"]
        g_avg = contour['color_avg']["g"]
        b_avg = contour['color_avg']["b"]
        r_std = contour['color_std']["r"]
        g_std = contour['color_std']["g"]
        b_std = contour['color_std']["b"]
        print('\t'.join([str(x) for x in (layer_id,
                         contour_id,
                         cell_label,
                         centroid[0],
                         centroid[1],
                         r_avg,
                         g_avg,
                         b_avg,
                         r_std,
                         g_std,
                         b_std )]))
