using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Kendo.Mvc.Examples.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System;

namespace Kendo.Mvc.Examples.Controllers
{
    public partial class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        private IList<ProductViewModel> Products
        {
            get
            {
                IList<ProductViewModel> products = Session["products"] as IList<ProductViewModel>;

                if (products == null)
                {
                    products = Enumerable.Range(1, 100).Select(index => new ProductViewModel
                    {
                        ProductID = index,
                        ProductName = "Product " + index,
                        LastSupply = DateTime.Now
                    }).ToList();

                    Session["products"] = products;
                }

                return products;
            }
        }

        public ActionResult ComboRead(string name) 
        {
            return Json(Products);
        }

        public ActionResult Editing_Read([DataSourceRequest] DataSourceRequest request, string kur)
        {

            return Json(Products.ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> products)
        {
            if (products != null && ModelState.IsValid)
            {
                foreach (var product in products)
                {
                    var target = Products.FirstOrDefault(p => p.ProductID == product.ProductID);
                    if (target != null)
                    {
                        target.ProductName = product.ProductName;
                        target.UnitPrice = product.UnitPrice;
                        target.UnitsInStock = product.UnitsInStock;
                        target.LastSupply = product.LastSupply;
                        target.Discontinued = product.Discontinued;
                    }
                }
            }

            return Json(products.ToDataSourceResult(request, ModelState));
        }

    }
}
