import json
import csv
from pathlib import Path
from island.match import Match
from island.matches import Matches

result = {}
userdata = {}
with open('user.data', 'r') as c:
    for row in csv.reader(c):
        userdata[int(row[0])] = {
            'uid': row[0],
            'name': row[1],
            'email': row[2]
        }
ms = Matches.from_profile_expr(lambda r: 'LAB' in r and 'CLASSIC' in r)
for m in ms.data:
    for r in m.query('user', 'fitness').raw_data:
        if r['user'] in result:
            result[r['user']]['rewards'] += float(r['fitness']) - 0.0001
            result[r['user']]['participate'] += 1
        else:
            result[r['user']] = {
                'rewards': float(r['fitness']) - 0.0001,
                'participate': 1
            }
ms = Matches.from_profile_expr(lambda r: 'LAB' in r and 'SURVIVE' in r)
for m in ms.data:
    for r in m.query('player', 'join').raw_data:
        if r['uid'] in result:
            result[r['uid']]['rewards'] += 5
            result[r['uid']]['participate'] += 1
        else:
            result[r['uid']] = {
                'rewards': 5.0,
                'participate': 1
            }
    for r in m.query('user', 'fitness').raw_data:
        result[r['user']]['rewards'] += float(r['fitness']) * 5

total = 0.0
with open('user.reward.csv', 'w') as out:
    writer = csv.writer(out)
    writer.writerow(['uid', 'name', 'email', 'reward', 'participates'])
    for k,v in result.items():
        writer.writerow([k, userdata[k]['name'], userdata[k]
                         ['email'], round(v['rewards'], 2), v['participate']])
        total += v['rewards']

print("total: %f" % (total))
