import csv
import numpy as np
from island.match import Match
from island.matches import Matches

def calc_and_save(mode):
    matches = Matches.from_profile(mode)
    ans = np.zeros(15)
    div = np.zeros(15)
    for m in matches.data:
        maxr = int(m.query('game', 'created').first()['info']['game_end_at'])
        for i in range(1, maxr):
            rows = m.query('action', 'done').where(lambda x: x['rno']==i).raw_data
            br = 0
            for r in rows:
                if m.query('action', 'done').where(lambda x: x['rno']==i+1 and ((x['a']==r['a'] and x['b']==r['b']) or (x['a']==r['b'] and x['b']==r['a']))).count() == 0:
                    br += 1
            ans[i] += br
            div[i] += len(rows)
    div[np.where(div==0)[0]] = 1
    ans /= div
    with open("outputs/BR_%s.csv"%mode, 'w') as f:
        csv.writer(f).writerow(ans)   

if __name__ == '__main__':
    calc_and_save('CLASSIC')
    calc_and_save('SURVIVE')
