using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.WebUtilities;
using economy.Helpers;
using economy.Models;
using economy.Models.Price.Domestic;
using economy.Models.Price.Domestic.Emission;

namespace economy.Controllers.Price.Domestic
{
    public class EmissionController : Controller
    {
        private readonly DataGoKR _dataGoKR;
        private Dictionary<string, string> _queryString;

        public EmissionController(DataGoKR dataGoKR)
        {
            _dataGoKR = dataGoKR;
            _queryString = [];
        }

        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/Domestic/Emission")]
        public async Task<IActionResult> Index(Request request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            DomesticModel domesticModel = new DomesticModel(_dataGoKR, null);
            Response itemList = await domesticModel.GetEmissionPriceInfo(request);

            if (itemList.Body is not null)
            {
                int listNum = Common.CalcListNumber(itemList.Body.TotalCount, request.PageNo, request.NumOfRows);
                itemList.Body.Items.ItemList = itemList.Body.Items.ItemList.Select((row, index) =>
                {
                    row.Num = listNum - index;
                    row.Clpr = Common.NumberFormat(row.Clpr);
                    row.Vs = Common.NumberFormat(row.Vs);
                    row.FltRt = Common.NumberFormat(row.FltRt, "0.##");
                    row.Mkp = Common.NumberFormat(row.Mkp);
                    row.Hipr = Common.NumberFormat(row.Hipr);
                    row.Lopr = Common.NumberFormat(row.Lopr);
                    row.Trqu = Common.NumberFormat(row.Trqu);
                    row.TrPrc = Common.NumberFormat(row.TrPrc);
                    return row;
                }).ToList();
            }

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

            var queryString = new
            {
                sDate = request.StartDate.ToString("yyyy-MM-dd"),
                eDate = request.EndDate.ToString("yyyy-MM-dd")
            };

            var pagination = new Pagination(itemList.Body?.TotalCount, request.PageNo, request.NumOfRows, queryString);
            viewModel.Pagination = pagination;

            return View("/Views/Price/Domestic/Emission.cshtml", viewModel);
        }
    }
}
