using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.WebUtilities;
using economy.Helpers;
using economy.Models;
using economy.Models.Financial;
using economy.Models.Price.Global;
using NaturalGas = economy.Models.Price.Global.NaturalGas;

namespace economy.Controllers.Price.Global
{
    public class GlobalController : Controller
    {
        private readonly Alpha_API _alphaAPI;
        private readonly KoreaEximGoKR _koreaEximGoKR;
        private Dictionary<string, string> _queryString;
        private int _exchangeValue = 0;

        public GlobalController(Alpha_API alphaAPI, KoreaEximGoKR koreaEximGoKR)
        {
            _alphaAPI = alphaAPI;
            _koreaEximGoKR = koreaEximGoKR;

            InitializeAsync();
        }

        // 초기화 메서드
        public async Task InitializeAsync()
        {
            // 환율 조회
            _exchangeValue = await new FinancialModel(_koreaEximGoKR).GetExchangeValue();
        }

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

        [HttpGet("Price/Global/NaturalGas")]
        public async Task<IActionResult> NaturalGas(NaturalGas.Request request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (!new[] { "daily", "weekly", "monthly" }.Contains(request.Interval))
            {
                return BadRequest("Invalid input provided.");
            }

            GlobalModel globalModel = new GlobalModel(_alphaAPI);
            NaturalGas.Response itemList = await globalModel.GetNaturalGasPriceInfo(request);

            int total = 0;

           if (itemList.Data != null && itemList.Data.Any())
            {
                total = itemList.Data.Count;
                int listNum = Common.CalcListNumber(total, request.PageNo, request.NumOfRows);

                // 페이징 처리
                int skip = (request.PageNo - 1) * request.NumOfRows;
                int take = request.NumOfRows;

                itemList.Data = itemList.Data.Skip(skip).Take(take).Select((row, index) =>
                {
                    row.Num = (listNum - index);

                    if (int.TryParse(row.Value, out int value) && value > 0)
                    {
                        row.KRW = (value * _exchangeValue);
                    }
                  
                    return row;
                }).ToList();
            }

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

            var queryString = new
            {
                date = request.Interval
            };

            var pagination = new Pagination(total, request.PageNo, request.NumOfRows, queryString);
            viewModel.Pagination = pagination;

            return View("/Views/Price/Global/NaturalGas.cshtml", viewModel);
        }
    }
}
