using Grid_MultiCheckBox_Filtering_of_Complex_Column_types.Models;
using Kendo.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.Infrastructure.Implementation;
using Kendo.Mvc.UI;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Grid_MultiCheckBox_Filtering_of_Complex_Column_types.Controllers
{
    public class GridController : Controller
    {
        public ActionResult Orders_Read([DataSourceRequest] DataSourceRequest request)
        {
            var filters = FilterDescriptorExtensions.SelectMemberDescriptors(request.Filters).AsQueryable();

            var categoryFilters = filters.Where(x => x.Member == "Category");

            
            var result = Enumerable.Range(1, 50).Select(i => new OrderViewModel
            {
                OrderID = i,
                Freight = i * 10,
                OrderDate = new DateTime(2016, 9, 15).AddDays(i % 7),
                Category = new CategoryModel() { CategoryID = i+15, CategoryName="Category "+i},
                ShipName = "ShipName " + i,
                ShipCity = "ShipCity " + i
            }).AsQueryable();
            result = CategoryFilter(result, categoryFilters);
            ModifyFilters(request.Filters);
            var dsResult = result.ToDataSourceResult(request);
            return Json(dsResult);
        }

        public IQueryable<OrderViewModel> CategoryFilter(IQueryable<OrderViewModel> orders,IQueryable<FilterDescriptor> categoryFilters)
        {
            IQueryable<OrderViewModel> filteredOrders = orders;
            foreach (var filter in categoryFilters)
            {
                var filterValue = filter.Value;
                filteredOrders = orders.Where(x=>x.Category.CategoryName==filter.Value.ToString());  
            }
            
            return filteredOrders;
        }
        private void ModifyFilters(IList<IFilterDescriptor> filters)
        {
            if (filters.Any())
            {
                for (int i = filters.Count - 1; i >= 0; i--)
                {
                    var filter = filters[i];
                    var descriptor = filter as FilterDescriptor;
                    if (descriptor != null && descriptor.Member == "Category")
                    {
                        var index = filters.IndexOf(filter);
                        filters.RemoveAt(index);
                    }
                    else if (filter is CompositeFilterDescriptor)
                    {
                        ModifyFilters(((CompositeFilterDescriptor)filter).FilterDescriptors);
                    }
                }
            }
        }
       
    }
}
