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

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

labels = ['has neighbor', 'no neighbor']
percents = [0.0, 0.0]
op = 'C'

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']
            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:
                pass
            else:
                o = m.query('action', 'done').where(lambda y: (y['b'] == b or y['a'] == 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']
            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:
                pass
            else:
                o = m.query('action', 'done').where(lambda y: (y['b'] == a or y['a'] == a) and y['rno'] == row['rno'] + 1).raw_data
                if o:
                    percents[0] += 1
                else:
                    percents[1] += 1

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

plt.figure()
plt.pie(percents, labels=labels, autopct='%1.1f%%', startangle=90)
plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
# plt.savefig('graph/unlink_has_neighbor.png')