'''
    download_data.py
    -------------------
    This module is used to download the data necessary to generate random
    hockey players.
'''

from urllib.request import urlopen
from collections import defaultdict
import json
import codecs
import os

URL = 'http://api.eliteprospects.com:80/beta/players'


def download_players():
    '''
    Downloads player information data from eliteprospect.
    '''

    number_of_players = get_data(URL)['metadata']['totalCount']
    names, countries = {}, defaultdict(int)

    for offset in range(0, number_of_players, 1000):

        players = get_data(URL + "?limit=1000" + "&offset=" + str(offset))

        for num, player in enumerate(players['data']):

            country = get_country(player)

            if not country:
                continue

            if country not in names:
                names[country] = dict([("fname", defaultdict(int)),
                                      ("lname", defaultdict(int))])

            names[country]["fname"][player["firstName"]] += 1
            names[country]["lname"][player["lastName"]] += 1
            countries[country] += 1

    save_dictionary("player_names.json", names)
    save_dictionary("countries.json", countries)

def download_draft():
    '''
    This is used to download information related to NHL Drafts. This will fetch
    past NHL drafts and information of the players drafted.
    '''

    pass

def get_data(url):
    '''
    Makes the request to the site to fetch the data.
    '''

    try:
        reader = codecs.getreader("utf-8")
        http = urlopen(url)
        return json.load(reader(http))
    except:
        print("Error fetching data.")

def get_country(player):
    '''
    Given a player JSON Object fetches the player home country.
    '''

    if "country" in player:
        return player["country"]["name"]

    if "birthPlace" in player:

        if "country" in player["birthPlace"]:
            return player["birthPlace"]["country"]["name"]

        return player["birthPlace"]["parentLocality"]["country"]["name"]

    return None


def save_dictionary(filename, dictionary):
    '''
    Converts a python dictionary into a json string and saves it with the given
    filename.
    '''

    if not os.path.isdir("data"):
        os.mkdir("data")

    json_data = json.dumps(dictionary)

    with open(os.path.join('data', filename), 'w') as output:
        output.write(json_data)

if __name__ == '__main__':
fn
    download_players()
