namespace RangeFilteringToolBar.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using Models;
    using Telerik.Web.Mvc;

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(GetOrders());
        }

        [GridAction]
        public ActionResult Select(DateTime? startDate, DateTime? endDate)
        {
            var orders = GetOrders();
            if (startDate.HasValue)
            {
                orders = orders.Where(o => o.OrderDate >= startDate);
            }

            if (endDate.HasValue)
            {
                orders = orders.Where(o => o.OrderDate <= endDate);
            }

            return Json(new GridModel(orders));
        }

        IEnumerable<OrderModel> GetOrders()
        {
            return new NorthwindDataContext().Orders.Select(o => new OrderModel
                                                              {
                                                                  ID = o.OrderID,
                                                                  CustomerName = o.Customer.CompanyName,
                                                                  EmployeeName = o.Employee.FirstName + o.Employee.LastName,
                                                                  OrderDate = o.OrderDate
                                                              });
        }
    }
}
