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


matches = Matches('wos-data-new-2')
max_round = 14

# c_req_succ = np.zeros(max_round-2)
# c_req = np.zeros(max_round-2)
# d_req_succ = np.zeros(max_round-2)
# d_req = np.zeros(max_round-2)

c_req_succ = np.zeros(max_round)
c_req = np.zeros(max_round)
d_req_succ = np.zeros(max_round)
d_req = np.zeros(max_round)

def is_cooperator(rows, pid):
    m = 0
    mall = 0
    for r in rows:
        if pid == r['a'] and r['act_a'] == 'C':
            m += 1
            mall += 1
        elif pid == r['a'] and r['act_a'] == 'D':
            mall += 1
        elif pid == r['b'] and r['act_b'] == 'C':
            m += 1
            mall += 1
        elif pid == r['b'] and r['act_b'] == 'D':
            mall += 1
    return m*2 >= mall

for i in range(max_round):
    for j in range(len(matches.data)):
        rows = matches.data[j].query('action', 'done').where(lambda x: x['rno'] == i+1).raw_data
        calced = set()
        for row in rows:
            if row['a'] not in calced:
                r = matches.data[j].query('action', 'request').where(lambda x: x['rno'] == i+2 and x['from'] == row['a']).raw_data
                rs = matches.data[j].query('action', 'approve').where(lambda x: x['rno'] == i+2 and x['to'] == row['a']).raw_data
                if is_cooperator(rows, row['a']):
                    c_req_succ[i] += len(rs)
                    c_req[i] += len(r)
                else:
                    d_req_succ[i] += len(rs)
                    d_req[i] += len(r)
                calced.add(row['a'])

            if row['b'] not in calced:
                r = matches.data[j].query('action', 'request').where(lambda x: x['rno'] == i+2 and x['from'] == row['b']).raw_data
                rs = matches.data[j].query('action', 'approve').where(lambda x: x['rno'] == i+2 and x['to'] == row['b']).raw_data
                if is_cooperator(rows, row['b']):
                    c_req_succ[i] += len(rs)
                    c_req[i] += len(r)
                else:
                    d_req_succ[i] += len(rs)
                    d_req[i] += len(r)
                calced.add(row['b'])

for i in range(len(c_req)):
    if c_req[i] == 0:
        c_req[i] = 0.1
    if d_req[i] == 0:
        d_req[i] = 0.1

c_req_succ_fr = c_req_succ / c_req
d_req_succ_fr = d_req_succ / d_req

print(c_req_succ)
print(c_req)
print(c_req_succ_fr)
print(d_req_succ)
print(d_req)
print(d_req_succ_fr)

req_succ_fr_mean = [mean(c_req_succ_fr), mean(d_req_succ_fr)]
req_succ_fr_sem = [std(c_req_succ_fr), std(d_req_succ_fr)]

req_succ = [c_req_succ_fr, d_req_succ_fr]

fig = plt.figure(figsize=(4, 3))
ax = fig.gca()
index = np.arange(2)
bar_width = 0.5
opacity = 1
error_config = {'ecolor': '0.3', 'capsize': 2, 'linewidth': 1}
# rects1 = ax.bar(index, req_succ_fr_mean, bar_width,
#                 alpha=opacity, color='#0984e3',
#                 yerr=req_succ_fr_sem, error_kw=error_config,
#                 label='C-Req-Success')
flier_marker = dict(markerfacecolor='w', marker='o', markersize=4, markeredgewidth=0.5)
mean_marker = dict(markerfacecolor='w', marker='s', markeredgecolor='#0984e3', markersize=5, markeredgewidth=1)
ax.boxplot(req_succ, showmeans=True, notch=True,
           meanprops=mean_marker, flierprops=flier_marker, 
           whis=[0.35,99.65], 
           widths=0.4,
           labels=['From Cooperator', 'From Defector'])

m1 = np.median(c_req_succ_fr)
m2 = np.median(d_req_succ_fr)
# i1 = np.subtract(*np.percentile(c_req_succ_fr, [75*0.98, 25*0.98]))
# i2 = np.subtract(*np.percentile(d_req_succ_fr, [75*0.98, 25*0.98]))
i1 = np.subtract(*np.percentile(c_req_succ_fr, [75, 25]))
i2 = np.subtract(*np.percentile(d_req_succ_fr, [75, 25]))



print('M=(%f, %f)' % (m1, m2))
print('IQR=(%f, %f)' % (i1, i2))


# ax.set_xlabel('Group')
ax.set_ylabel('Request Approval Rate')
# ax.set_title(' from ', fontsize='small', weight='semibold')
# ax.set_xticks(index)
# ax.set_ylim(0, 1)
# ax.set_xlim(-0.75, 1.75)
# ax.set_xticklabels(index+2)
# ax.legend()
fig.tight_layout()
plt.show()
# plt.savefig('graph/request_success.eps')