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

namespace economy.Controllers.Price.Domestic
{
    public class FlowerController : Controller
    {
        private readonly FlowerAtOrKR _flowerAtOrKR;
        private Dictionary<string, string> _queryString;

        public FlowerController(FlowerAtOrKR flowerAtOrKR)
        {
            _flowerAtOrKR = flowerAtOrKR;
            _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/Flower")]
        public async Task<IActionResult> Index(Request request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            DomesticModel domesticModel = new DomesticModel(null, _flowerAtOrKR);
            Response itemList = await domesticModel.GetFlowerPriceInfo(request);

            if (itemList is not null)
            {
                int listNum = Common.CalcListNumber(itemList.NumberOfRows, request.PageNo, request.NumOfRows);
                itemList.Items = itemList.Items.Select((row, index) =>
                {
                    row.Num = listNum - index;
                    row.MaxAmt = Common.NumberFormat(row.MaxAmt);
                    row.MinAmt = Common.NumberFormat(row.MinAmt);
                    row.AvgAmt = Common.NumberFormat(row.AvgAmt);
                    row.TotAmt = Common.NumberFormat(row.TotAmt);
                    row.TotQty = Common.NumberFormat(row.TotQty);
                    return row;
                }).ToList();
            }

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

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

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

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