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

namespace DetailGrids.Controllers
{
	public partial class GridController : Controller
    {
        public static List<OrderViewModel> orders = Enumerable.Range(1, 3).Select(i => new OrderViewModel
		{
				OrderID = i,
				Freight = i* 10,
				OrderDate = DateTime.Now.AddDays(-i),
				ShipName = "ShipName " + i,
				ShipCity = "ShipCity " + i,
                EmployeeID = i == 0 ? new Nullable<int>() : i -1
		}).ToList();

        public static Random random = new Random();

        public static List<InventoryDetail> details =  Enumerable.Range(1, 50).Select(i => new InventoryDetail
        {
                ItemCode = "ItemCode" + i,
                Allocated = i* 10,
                Bin = "Bin " + i* 5,
                OnHand = i* 7,
                OnOrder = i* 2,
                Warehouse = "Warehouse " + i,
                OrderID = orders.ElementAt(random.Next(0, orders.Count)).OrderID

        }).ToList();
		public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
		{
			return Json(orders.ToDataSourceResult(request));
		}

        public ActionResult Orders_Update([DataSourceRequest]DataSourceRequest request, OrderViewModel order)
        {
            for (int i = 0; i < orders.Count; i++)
            {
                if (orders[i].OrderID == order.OrderID)
                {
                    orders[i] = order;
                    break;
                }
            }

            return Json(new[] { order }.ToDataSourceResult(request));
        }

        public ActionResult InventoryDetail_Read([DataSourceRequest]DataSourceRequest request, int orderID)
        {
            var result = details.FindAll(d => d.OrderID == orderID);
            return Json(result.ToDataSourceResult(request));
        }

        public ActionResult InventoryDetail_Update([DataSourceRequest]DataSourceRequest request, InventoryDetail inventory)
        {
            for (int i = 0; i < details.Count; i++)
            {
                if (details[i].ItemCode == inventory.ItemCode) {
                    details[i] = inventory;
                    break;
                }
            }

            return Json(new[] { inventory }.ToDataSourceResult(request));
        }
    }
}
