using AS1024.CommunityDocumentationPage.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using NetBox;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;

namespace AS1024.CommunityDocumentationPage.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private IConfiguration Configuration { get; }

        public HomeController(ILogger<HomeController> logger,
            IConfiguration configuration)
        {
            _logger = logger;
            Configuration = configuration;
        }

        public async Task<IActionResult> IndexAsync()
        {
            var results = await ReadAPI(Configuration["APIKey"]);

            var filtered = results.Results.Where(b => b.Name.StartsWith(Configuration["ASN"]))
                .ToList();

            return View(filtered);
        }

        private static async Task<RouteTargets> ReadAPI(string token)
        {
            try
            {
                HttpClient client = new();
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", token);
                var result = await client.GetAsync("https://netbox.as1024.net/api/ipam/route-targets/");
                var stringResult = await result.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<RouteTargets>(stringResult);
            } catch
            {
                throw new Exception("Something went wrong?");
            }
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}