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

namespace TelerikAspNetCoreApp424.Controllers
{
    public class GridController : Controller
    {
        public ActionResult Orders_Read([DataSourceRequest] DataSourceRequest request)
        {
            var result = Enumerable.Range(1, 50).Select(i => new OrderViewModel
            {
                OrderID = i,
                Freight = i * 10,
                OrderDate = new DateTime(2016, 9, 15).AddDays(i % 7).Date,
                ShipName = "ShipName " + i,
                ShipCity = "ShipCity " + i
            });

            var dsResult = result.ToDataSourceResult(request);
            return Json(dsResult);
        }

        public ActionResult Orders_Update([DataSourceRequest] DataSourceRequest request, OrderViewModel model)
        {
            var result = Enumerable.Range(1, 50).Select(i => new OrderViewModel
            {
                OrderID = i,
                Freight = i * 10,
                OrderDate = new DateTime(2016, 9, 15).AddDays(i % 7).Date,
                ShipName = "ShipName " + i,
                ShipCity = "ShipCity " + i
            });


            var existingModel = result.FirstOrDefault(f => f.ShipName == model.ShipName);

            if (existingModel != null)
            {
                ModelState.AddModelError("ShipName", "Name is already present within the collection");
            }
            
            return Json(new[] { model }.ToDataSourceResult(request, ModelState));
        }
    }
}
