import datetime
import json
import os
from pprint import pprint
import pandas as pd
from requests import get

inicio = datetime.datetime.now()
tabela = []
url = "https://api.clashroyale.com/v1/locations"
headers = {
  'Accept': 'application/json',
  'authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2'
                   'NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6IjI5NzIwYmYzLWFlYWUtNDV'
                   'iYS04NGJkLWI2YTA5YTNiOGI5NyIsImlhdCI6MTYyNTQyODE3MCwic3ViIjoiZGV2ZWxvcGVyLzI1Y2UxYjM2LTE1YzktZmMzOS'
                   '0'
                   '4YzFlLTVlY2JmNTg5MTJiOSIsInNjb3BlcyI6WyJyb3lhbGUiXSwibGltaXRzIjpbeyJ0aWVyIjoiZGV2ZWxvcGVyL3NpbHZlci'
                   'Is'
                   'InR5cGUiOiJ0aHJvdHRsaW5nIn0seyJjaWRycyI6WyIyMDEuNDIuMTU4LjI5Il0sInR5cGUiOiJjbGllbnQifV19.VTJGotqvum'
                   '5Ow'
                   'a4COy86uoU8gCCDxUHR-xSqtUDGpONavDV1xTRTN4SUuJTzc8Vp1zd6e23OXuD9BJfluPeQmA'
}
reponse = get(url, headers=headers)
countries = {}
countries = {w['id']: w['name'] for w in json.loads(reponse.text)['items']}
# brazil = 57000038
id_country = 57000038
for item in countries.items():
    url_get_players_by_id_country = f'https://api.clashroyale.com/v1/locations/{item[0]}/rankings/players'
    response = get(url_get_players_by_id_country, headers=headers)
    name_pais = item[1]
    if response.status_code == 200:
        for r in json.loads(response.text)['items']:
            item = {}
            try:
                item["name_pais"] = name_pais
                item["name"] = r["name"]
                item["tag"] = r["tag"]
                item["rank"] = r["rank"]
                item["expLevel"] = r["expLevel"]
                item["trophies"] = r["trophies"]
                if "clan" in r:
                    item["name_clan"] = r["clan"]["name"]
                    item["tag_clan"] = r["clan"]["tag"]
                else:
                    item["name_clan"] = None
                    item["tag_clan"] = None
                item["id_arena"] = r["arena"]["id"]
                item["name_arena"] = r["arena"]["name"]
                tabela.append(item)
                pprint(item)
                print(f'{"-"*80}')
            except Exception:
                continue

fim = datetime.datetime.now()
file_to_save_json = "players.json"
homepath = os.path.expanduser(os.getenv("USERPROFILE"))
desktoppath = "Desktop"
local_filename_json = os.path.join(homepath, desktoppath, file_to_save_json)
dict_salvar = json.dumps(tabela, indent=4, ensure_ascii=False)
try:
    file = open(local_filename_json, "w", encoding="utf8")
    file.write(dict_salvar)
    file.close()
except Exception as erro:
    print("Ocorreu um erro ao carregar o arquivo.")
    print("O erro é: {}".format(erro))

# passar de json para csv

file_name = u"players.csv"
file_to_save_csv = os.path.join(homepath, desktoppath, file_name)
df = pd.read_json(local_filename_json)
df.to_csv(file_to_save_csv, encoding="utf-8", index=False)
print(fim - inicio)
