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.Oil;

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

        public OilController(DataGoKR dataGoKR)
        {
            _dataGoKR = dataGoKR;
        }

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

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

            if (itemList 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.OilCtg = Common.NumberFormat(row.OilCtg);
                    row.WtAvgPrcCptn = Common.NumberFormat(row.WtAvgPrcCptn, "0.##");
                    row.WtAvgPrcDisc = Common.NumberFormat(row.WtAvgPrcDisc);
                    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/Oil.cshtml", viewModel);
        }
    }
}
