from datetime import datetime
import json
import crawers


def get_crawer(ojname: str):
    if not hasattr(get_crawer, "list"):
        get_crawer.list = {
            "vjudge": crawers.vjudge_crawer
        }
    return get_crawer.list[ojname]


def load_users():
    with open("users.json") as f:
        users_raw = json.load(f)
    return users_raw['users']


def save_users(users):
    with open("result.json", "w") as f:
        json.dump({"version": int(datetime.now().timestamp() * 1000), "users": users}, f)


def merge_result(results: list):
    solved = {}
    for result in results:
        for oj in result:
            if oj not in solved:
                solved[oj] = set()
            solved[oj] = solved[oj].union(result[oj])
    ret = {}
    for oj in solved:
        ret[oj.lower()] = list(solved[oj])
    return ret


def __main__():
    users = load_users()
    for user in users:
        print(user['uid'], user['name'], ':')
        user['result'] = merge_result([get_crawer(rec['oj'])(rec['id']) for rec in user['ids']])
    save_users(users)


if __name__ == '__main__':
    __main__()
