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

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

lx=[]
ly=[]

h = []

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:
                h.append(n[0]['tr'])
                if n[0]['tr'] in lx:
                    ly[lx.index(n[0]['tr'])] += 1
                else:
                    lx.append(n[0]['tr'])
                    ly.append(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:
                h.append(n[0]['tr'])
                if n[0]['tr'] in lx:
                    ly[lx.index(n[0]['tr'])] += 1
                else:
                    lx.append(n[0]['tr'])
                    ly.append(1)

al = sum(ly)

ly = map(lambda y: float(y) / float(al), ly)

_bin = [x * 120 for x in range(13)]

fig = plt.figure()
n,b,p = plt.hist(h, _bin, normed=True, ec='k')
ax = fig.gca()
ax.yaxis.set_major_formatter(PercentFormatter(xmax=sum(n)))
print(n)
print(b)
print(p)
print(sum(n))
# plt.show()
plt.savefig('graph/after_d_link_tr.png')