using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.WebUtilities;
using economy.Models;
using economy.Models.FIFA;

namespace economy.Controllers
{
    public class FIFAController : Controller
    {
        private readonly FIFA_API _fifaAPI;
        private Dictionary<string, string> _queryString;

        public FIFAController(FIFA_API fifaAPI)
        {
            _fifaAPI = fifaAPI;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            _queryString = QueryHelpers.ParseQuery(HttpContext.Request.QueryString.Value).ToDictionary(k => k.Key, v => string.Join(",", v.Value));

            ViewBag.QueryString = _queryString;

            base.OnActionExecuting(context);
        }

        public async Task<IActionResult> Index(Request request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            FIFAModel fifa = new FIFAModel(_fifaAPI);
            Response itemList = await fifa.GetRanking(request);

            if (itemList is not null)
            {
                itemList.Results = itemList.Results
                  .Select((row, index) =>
                  {
                      row.Num += 1;
                      row.FlagSrc = $"https://api.fifa.com/api/v3/picture/flags-sq-4/{row.IdCountry}";
                      return row;
                  })
                  .ToList();

                string ?type = request.Type.ToString();
                if (itemList.Results is not null && type != string.Empty)
                {
                    itemList.Results = itemList.Results.Where(row => row.ConfederationName == type).ToList();
                }
            }

            var viewModel = new View<Request, Response>();
            viewModel.SelectedListPerPage = request.NumOfRows;
            viewModel.Request = request;
            viewModel.Response = itemList;

            return View(viewModel);
        }
    }
}
