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

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Categories = GetCategories();
            return View();
        }

        [GridAction]
        public JsonResult Select()
        {
            return Json(GetProducts());
        }

        [HttpPost]
        [GridAction]
        public JsonResult Update(int id)
        {
            using (var db = new Northwind())
            {
                var product = db.Products.First(p => p.ProductID == id);
                if (TryUpdateModel(product))
                {
                    db.SaveChanges();
                }
            }
            return Json(GetProducts());
        }

        [HttpPost]
        [GridAction]
        public JsonResult Insert()
        {
            var product = new Product();
            if (TryUpdateModel(product))
            {
                using (var db = new Northwind())
                {
                    db.Products.Add(product);
                    db.SaveChanges();
                }
            }
            return Json(GetProducts());
        }

        [HttpPost]
        [GridAction]
        public JsonResult Delete(int id)
        {
            using (var db = new Northwind())
            {
                var product = db.Products.First(p => p.ProductID == id);
                db.Products.Remove(product);
                db.SaveChanges();
            }
            return Json(GetProducts());
        }


        public IEnumerable<ProductsViewModel> GetProducts()
        {
            var db = new Northwind();
            return db.Products.Select(p => new ProductsViewModel
                                               {
                                                   ProductID = p.ProductID,
                                                   ProductName = p.ProductName,
                                                   UnitPrice = p.UnitPrice,
                                                   CategoryID = p.Category.CategoryName,
                                                   Discontinued = p.Discontinued
                                               }).ToList();
        }

        public IEnumerable<Category> GetCategories()
        {
            var db = new Northwind();
            return db.Categories.ToList();
        }
    }
}