using System;
using System.Linq;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using System.Collections.Generic;

namespace CarErrorSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.CarTypes = (new Models.CarType()).CarTypes;
            ViewBag.Countries = (new Models.Country()).Countries;
            return View();
        }

        [GridAction]
        public ActionResult _SelectCar()
        {            
            return View(new GridModel(Cars()));
        }

        [GridAction]
        [HttpPost]
        public ActionResult _UpdateCar(ViewModels.Car car)
        {
            Models.Car item = new Models.Car();
            if (ModelState.IsValid)
            {
                TryUpdateModel(item);
                var type = (new Models.CarType()).CarTypes.Where(t => t.Name == car.Type).Single();
                item.TypeId = type.Id;
                // save process
            }
            return View(new GridModel(Cars()));

        }
        public ActionResult About()
        {
            return View();
        }

        private IEnumerable<ViewModels.Car> Cars()
        {
            var types = (new Models.CarType()).CarTypes;
            var countries = (new Models.Country()).Countries;
            var data = Models.Car.Cars().Select(t => new ViewModels.Car()
            {
                Model = t.Model,
                Name = t.Name,
                Weight = t.Weight,
                Type = types.Where(x => x.Id == t.TypeId).Single().Name,
                Country=countries.Where(x=>x.Id==t.CountryId).Single().Name,
            });
            ViewBag.CarTypes = types;
            ViewBag.Countries = countries;
            return data;
        }
    }
}
