using AS1024.CommunityDocumentationPage.Interfaces;
using AS1024.CommunityDocumentationPage.Models;
using System.Text.Json;
using System.Net.Http.Headers;

namespace AS1024.CommunityDocumentationPage.DIScopes
{
    public class NetBoxBgpCommunities : IBgpCommunity
    {
        protected readonly IConfiguration _configuration;
        public NetBoxBgpCommunities(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        string IBgpCommunity.DcimName => "netbox";

        public async Task<ICollection<CommunityTag>> GetCommunities()
        {
            var Tags = new List<CommunityTag>();
            using HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", _configuration["APIKey"]);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage result = await client.GetAsync(BuildNetBoxURI());
            string stringResult = await result.Content.ReadAsStringAsync();
            var temp =
                JsonSerializer.Deserialize<RouteTargets>(stringResult, new JsonSerializerOptions{
                    PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
                });

            foreach (var route in temp.Results)
            {
                var community = new CommunityTag
                {
                   ASN = int.Parse(route.Name.Split(':')[0]),
                   CommunityValue = int.Parse(route.Name.Split(':')[1]),
                   Description = route.Description,
                   Tag = route.Tags
                };
                Tags.Add(community);
            }

            return Tags.OrderBy(b => b.ASN)
                .ThenBy(b => b.CommunityValue)
                .ToList();
        }

        protected Uri BuildNetBoxURI()
        {
            UriBuilder endUrl = new UriBuilder
            {
                Path = "/api/ipam/route-targets/",
                Host = _configuration["NetBoxHost"],
                Scheme = "https"
            };

            return endUrl.Uri;
        }
    }
}
