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

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

labels = ['link', 'unlink']
percents = [0.0, 0.0]

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'] == 'D' or x['act_b'] == 'D').raw_data:
        if row['rno'] == game_end_at:
            print(row)
            continue
        if row['act_a'] == 'D':
            a = row['a']
            b = row['b']
            n = m.query('action', 'done').where(lambda y: ((y['a'] == a and y['b'] == b) or (y['a'] == b and y['b'] == a)) and y['rno'] == row['rno'] + 1).raw_data
            if n:
                percents[0] += 1
            else:
                percents[1] += 1
        if row['act_b'] == 'D':
            a = row['a']
            b = row['b']
            n = m.query('action', 'done').where(lambda y: ((y['a'] == a and y['b'] == b) or (y['a'] == b and y['b'] == a)) and y['rno'] == row['rno'] + 1).raw_data
            if n:
                percents[0] += 1
            else:
                percents[1] += 1

_all = sum(percents) / 100
percents[0] /= _all
percents[1] /= _all

plt.figure()
patches, texts, autotexts = plt.pie(percents, labels=labels, autopct='%1.1f%%', startangle=90)

for t in texts:
    t.set_size('xx-large')

plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
# plt.savefig('graph/actions_after_defect.png')