import json
from matplotlib import pyplot as plt
from island.match import Match
from island.matches import Matches
import numpy as np

matches = Matches('wos-data-new')
max_round = 15

alive = []
yerr = []
x = []
al_al = []
d = []
d_sem = []

survivals = {}
with open('winner.json','r') as f:
    survivals = json.load(f)

for i in range(max_round):
    defects = []
    count = []
    for j in range(len(matches.data)):
        defector = set()
        for row in matches.data[j].query('action', 'done').where(lambda x: x['rno']==i+1 and (x['act_a']=='D' or x['act_b']=='D')).raw_data:
            if row['act_a']=='D':
                defector.add(row['a'])
            if row['act_b'] == 'D':
                defector.add(row['b'])

        if defector:
            # print("[%d,%d] %s" % (i,j,str(defector)))
            incr = 0
            for k in survivals[matches.names[j]]:
                if k in defector:
                    incr += 1
                    # print(k)
            defects.append(float(incr) / float(len(defector)))
            count.append(len(defector))
    print(i)
    print(defects)
    print(count)
    if defects:
        defects = np.array(defects)
        al_al.append(defects)
        alive.append(np.average(defects))
        yerr.append(np.std(defects))
        count = np.array(count)
        d.append(np.average(count))
        d_sem.append(np.std(count))
    else:
        al_al.append([])
        alive.append(0)
        yerr.append(0)
        d.append(0)
        d_sem.append(0)
    x.append(i+1)


fig = plt.figure(figsize=(6.4, 4))
flier_marker = dict(markerfacecolor='w', marker='o', markersize=3, markeredgewidth=0.5)
mean_marker = dict(markerfacecolor='w', marker='s', markeredgecolor='#0984e3', markersize=3, markeredgewidth=1)
ax1 = fig.gca()
# plt.errorbar(x, alive, yerr=[yerr_min, yerr_max], fmt='o', capsize=4)
ax1.boxplot(al_al, showmeans=True, meanprops=mean_marker, flierprops=flier_marker)
plt.xlabel('Round')
plt.ylabel('Frequency of Defection Survivals')
# ax2 = ax1.twinx()
# ax2.errorbar(list(range(1, max_round+1)), d, yerr=d_sem, fmt='o-', capsize=2, color='#00b894', alpha=0.5, linewidth=1, zorder=-1)
# ax2.errorbar(x, alive, yerr=yerr, fmt='o-', capsize=2, color='#00b894', alpha=0.5, linewidth=1, zorder=-1)
# ax2.tick_params(axis='y', labelcolor='#00b894')
plt.tight_layout()
plt.show()
# plt.savefig('graph/survive_after_defect.png')