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

mode = 'SURVIVE'
matches = Matches.from_profile_expr(lambda r: mode in r)

labels = ['Stay Connected', 'Break Tie']
percents = [0.0, 0.0]
op = 'D'

for m in matches.data:
    info = m.query('game', 'created').select('info').first()['info']
    conf = json.loads(info['config'])
    game_end_at = int(info['game_end_at'])

    for row in m.query('action', 'done').where(lambda x: x['act_a'] == op or x['act_b'] == op).raw_data:
        if row['rno'] == game_end_at:
            # print(row)
            continue
        if row['act_a'] == op:
            a = row['a']
            b = row['b']
            o = m.query('action', 'done').where(lambda y: ((y['b'] == a and y['a'] == b) or (y['a'] == a and y['b'] == b)) and y['rno'] == row['rno'] + 1).raw_data
            if o:
                percents[0] += 1
            else:
                percents[1] += 1
        if row['act_b'] == op:
            a = row['a']
            b = row['b']
            o = m.query('action', 'done').where(lambda y: ((y['b'] == a and y['a'] == b) or (y['a'] == a and y['b'] == b)) and y['rno'] == row['rno'] + 1).raw_data
            if o:
                percents[0] += 1
            else:
                percents[1] += 1
                
print(percents)
_all = sum(percents) / 100
percents[0] /= _all
percents[1] /= _all
print(percents)


plt.figure()
plt.pie(percents, labels=labels, autopct="%1.2f%%", pctdistance=1.1, labeldistance=2,startangle=90, colors=['#00b894', '#fdcb6e'])
plt.legend()
plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
# plt.savefig("graph/break_tie_%s_%s.eps"%(op, mode))
