import json
import sys
from matplotlib import pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

if __name__ == "__main__":
    cb = int(sys.argv[1])
    with open("outputs/cluster_life_%d.json" % cb) as f:
        raw = json.load(f)
    idx = []
    data = []
    if raw:
        for k in sorted(map(int, raw.keys())):
            idx.append(k)
            data.append(np.array(raw[str(k)]))
    if cb == 1:
        fig = plt.figure(figsize=(7.5,3))
    else:
        fig = plt.figure(figsize=(3,3))
    ax = fig.gca()
    bp = ax.boxplot(data, labels=idx)#, boxprops=dict(facecolor='lightblue'))
    ax.plot(np.arange(1, len(idx)+1), [np.mean(r) for r in data], '^-', color='green', linewidth=1, alpha=0.8)
    ax.set_xlabel("Cluster size")
    ax.set_ylabel("Cluster life")
    # for patch in bp['boxes']:
        # patch.set_facecolor('lightblue')

    for i in range(len(idx)):
        box = bp['boxes'][i]
        boxX = []
        boxY = []
        for j in range(5):
            boxX.append(box.get_xdata()[j])
            boxY.append(box.get_ydata()[j])
        boxCoords = list(zip(boxX, boxY))
        boxPolygon = Polygon(boxCoords, facecolor='lightblue')
        ax.add_patch(boxPolygon)
    fig.tight_layout()
    # plt.show()
    plt.savefig("graph/cluster_%d_life.eps" % cb)
