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

def calc_co(matches, is_casual):
    x = [0,0,0,0,0,0]
    count = 0
    for j in range(len(matches.data)):
        if len(matches.data[j].query('action', 'done').raw_data) < 5:
            continue
        coop = 0
        total = 0
        count += 1
        players = []
        if is_casual:
            for row in matches.data[j].query('player', 'join').where(lambda r: 'bot' not in r).raw_data:
                players.append(row['pid'])

        rows = matches.data[j].query('action', 'done').raw_data
        if is_casual:
            for row in rows:
                if row['a'] in players:
                    total += 1
                    if row['act_a'] == 'C':
                        coop += 1
                if row['b'] in players:
                    total += 1
                    if row['act_b'] == 'C':
                        coop += 1
        else:
            for row in rows:
                if row['act_a'] == 'C':
                    coop += 1
                if row['act_b'] == 'C':
                    coop += 1
                total += 2

        if rows:
            per = float(coop) / total
            x[int(per*100)//20] += 1
    x[4] += x[5]
    x.pop()
    s = sum(x)
    for i in range(5):
        x[i] /= s

    print("Match type: %s, Count: %d" % ('Casual' if is_casual else 'Compete', count))
    return x

casual = Matches('wos-data-casual')
compete = Matches('wos-data-new')

ca = calc_co(casual, True)
co = calc_co(compete, False)

fig = plt.figure(figsize=(5,4))
ax = fig.gca()
index = np.arange(5)
bar_width = 0.35
rects1 = ax.bar(index, ca, bar_width, color='#00b894', label='Casual mode')
# rects2 = ax.bar(index + bar_width, co, bar_width, color='#005CAF', label='Competition')
rects2 = ax.bar(index + bar_width, co, bar_width, color='#6c5ce7', label='Competing mode')

ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(['0~0.2','0.2~0.4','0.4~0.6','0.6~0.8','0.8~1'])
ax.legend()
# fig.autofmt_xdate()
fig.set_size_inches(5, 4)
plt.xlabel('Frequency of Human Cooperations per Match')
plt.ylabel('Fraction of Matches')
fig.tight_layout()

# plt.show()
plt.savefig('graph/CompCoPerMatch.eps')