import json

import requests


async def get_data_bf6(player_id, user_id, platform):
    url = "https://api.gametools.network/bf6/multiple/?raw=false&format_values=true"
    payload = json.dumps([
        {
            "player_id": player_id,
            "user_id": user_id,
            "platform": platform
        }
    ])

    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    info = json.loads(response.text)
    return info


async def get_data_user(user_name, platform):
    url = f"https://api.gametools.network/bfglobal/player/?name={user_name}&platform={platform}&skip_battlelog=false"

    payload = {}
    headers = {
        'accept': 'application/json'
    }

    response = requests.request("GET", url, headers=headers, data=payload)
    data_json = json.loads(response.text)

    player_id = data_json["personaId"]
    user_id = data_json["userId"]
    platform = data_json["platform"]
    user_name = data_json["personaName"]

    if "errors" in data_json:
        return False, data_json

    user_info = {
        "player_id": player_id,
        "user_id": user_id,
        "platform": platform,
        "user_name": user_name
    }

    return True, user_info


async def get_player_game_info(user_name, platform):
    flag, user_info = await get_data_user(user_name, platform)
    info = await get_data_bf6(user_info['player_id'], user_info['user_id'], user_info['platform'])
    info['userName'] = user_name
    info_format = json.dumps(info, ensure_ascii=False, indent=2)
    print(info_format)
