import json
from pathlib import Path

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator


def read_and_plot(json_file):
    graph_dir = Path('/Users/wjsjwr/lab/code/swdata/graph/')
    dpath = Path(json_file)
    with open(json_file, 'r') as f:
        data = json.load(f)

    actions = ''
    rnds = ''
    for d in data:
        if d['cat'] == 'game' and d['act'] == 'created':
            actions = np.zeros((2, int(d['info']['game_end_at'])), dtype=np.int32)
            rnds = list(range(1,int(d['info']['game_end_at'])+1))
            break
    
    for d in data:
        if d['cat'] == 'action' and d['act'] == 'done':
            actions[0 if d['act_a'] == 'C' else 1, int(d['rno'])-1] += 1
            actions[0 if d['act_b'] == 'C' else 1, int(d['rno'])-1] += 1
    
    plt.clf()
    lines = []
    lg = ['C', 'D']
    l, = plt.plot(rnds, actions[0,:], color='#FF358B', linewidth=1)
    lines.append(l)
    l, = plt.plot(rnds, actions[1,:], color='#01B0F0', linewidth=1)
    lines.append(l)
    plt.figlegend(lines, lg, numpoints=1, loc='upper right')
    fname = "act_rnd_%s.eps" % str(dpath.stem)
    plt.savefig(str(graph_dir / fname))

itr = Path('/Users/wjsjwr/lab/wos-data-new/')
for d in itr.iterdir():
    if d.suffix == '.json':
        read_and_plot(str(d))
        print(str(d))
