using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Example.Models;

namespace Example.Connectors
{
    public class GetPlayerInfo
    {
        public static PlayerInfoModule PlayerDetails = new PlayerInfoModule();
        public static minigame PlayerminigameStats = new minigame();
        public static minigame PlayerminigameStatsRank = new minigame();
        public static async Task<PlayerInfoModule> LoadPlayerData(string player_id, string serverPort)
        {
            try
            {
                string apiurl = $"https://api.whalleybot.com/bot/{serverPort}/GetPlayer/{player_id}";

                var handler = new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                };

                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Add("Authorization", "WhalleyBotOverlay_e-H1rr55f");
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    var response = await client.GetAsync(apiurl)
                        .ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        var json = response.Content.ReadAsStringAsync().Result;
                        
                        PlayerDetails = JsonConvert.DeserializeObject<PlayerInfoModule>(json);
                        if (PlayerDetails.minigameStatAllString != null)
                        {
                            PlayerminigameStats = JsonConvert.DeserializeObject<minigame>(PlayerDetails.minigameStatAllString);
                            PlayerminigameStatsRank = JsonConvert.DeserializeObject<minigame>(PlayerDetails.minigameStatRankString);
                        }
                        return PlayerDetails; ;
                    }
                    else
                    {
                        throw new Exception(response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Source + ex.Message + ex.Data + ex.StackTrace);
                return null;
            }
        }
    }
}
