using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CascadingComboBox_Demo.Models;
using Microsoft.AspNetCore.Mvc;

namespace CascadingComboBox_Demo.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
        public JsonResult GetCategories()
        {
            var categories = Enumerable.Range(0, 10).Select(i => new CategoryViewModel
            {
                CategoryID = i,
                CategoryName = "Category " + i
            });
            return Json(categories);
        }

        public JsonResult GetCascadeProducts(int? categories, string productFilter)
        {
            
                var products = Enumerable.Range(0, 50).Select(i => new ProductViewModel
                {
                    CategoryID = i % 10,
                    ProductID = i,
                    ProductName = "Product " + i
                });

            if (categories != null)
                {
                    products = products.Where(p => p.CategoryID == categories);
                }

            if (!string.IsNullOrEmpty(productFilter))
            {
                products = products.Where(p => p.ProductName.Contains(productFilter));
            }

            return Json(products.Select(p => new { ProductID = p.ProductID, ProductName = p.ProductName }).ToList());
            
        }
        public JsonResult GetCascadeOrders(int? products, string orderFilter)
        {

            var orders = GetOrders();

                if (products != null)
                {
                    orders = orders.Where(o => o.ProductID == products);
                }

                if (!string.IsNullOrEmpty(orderFilter))
                {
                    orders = orders.Where(o => o.ShipCity.Contains(orderFilter));
                }

                return Json(orders.Select(o => new { OrderID = o.OrderID, ShipCity = o.ShipCity }).ToList());
        }

        private IEnumerable<OrderViewModel> GetOrders()
        {
            var result = Enumerable.Range(0, 5000).Select(i => new OrderViewModel
            {
                OrderID = i,
                ProductID = i % 50,
                Freight = i * 10,
                OrderDate = DateTime.Now.AddDays(i),
                ShipName = "ShipName " + i,
                ShipCity = "ShipCity " + i,
            });

            return result;
        }
    }
}
