using AS1024.CommunityDocumentationPage.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using AS1024.CommunityDocumentationPage.Interfaces;

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

        public HomeController(ILogger<HomeController> logger,
            IConfiguration configuration, IBgpCommunityDocumentation documentation)
        {
            _logger = logger;
            _configuration = configuration;
            _documentation = documentation;
        }

        [ResponseCache(Duration = 3600)]
        public async Task<IActionResult> Index()
        {
            try
            {
                RouteTargets results = await _documentation.GetBgpCommunities();
                List<Result> filtered = results.Results.Where(b => b.Name.StartsWith(_configuration["ASN"]))
                    .ToList();

                return View(filtered);
            } catch (Exception ex)
            {
                _logger.LogError($"Failed to obtain data\n{ex}");
            }

            return NotFound();
        }

        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 });
        }
    }
}