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
{
    internal class APIGetSquads
    {

        public static List<SquadsModel> _SquadsList = new List<SquadsModel>();
        public static async Task<Dictionary<string, SquadsModel>> GetSquadsList(string serverPort)
        {
            try
            {
                string apiurl = $"https://api.whalleybot.com/bot/{serverPort}/GetSquads";
                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);
                    //var response = apicall.GetAwaiter().GetResult();
                    if (response.IsSuccessStatusCode)
                    {
                        var json = response.Content.ReadAsStringAsync().Result;

                        //_SquadsList = JsonConvert.DeserializeObject<List<SquadsModel>>(json);

                        //return _SquadsList;

                        Dictionary<string, SquadsModel> squads = JsonConvert.DeserializeObject<Dictionary<string, SquadsModel>>(json);

                        if (response.ReasonPhrase == "Newtonsoft.JsonError")
                        {
                            return null;

                        }

                        return squads;
                    }
                    else
                    {
                        throw new Exception(response.ReasonPhrase + response.StatusCode);
                    }

                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Source + ex.Message + ex.Data + ex.StackTrace);
                return null;
            }
        }
    }
}
