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

namespace AddItemToVirtualized.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(GetAll().ToDataSourceResult(request));
        }

        public ActionResult Create()
        {
            var tasks = GetAll();
            var newItem = new ItemViewModel() { Id = tasks.Count + 10, Name = "Added" };
            tasks.Add(newItem);
            HttpContext.Session["tasks"] = tasks;

            return Json(newItem, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ValueMapper(int[] values)
        {
            var indices = new List<int>();

            if (values != null && values.Any())
            {
                var index = 0;

                foreach (var order in GetAll())
                {
                    if (values.Contains(order.Id))
                    {
                        indices.Add(index);
                    }

                    index += 1;
                }
            }

            return Json(indices, JsonRequestBehavior.AllowGet);
        }

        private IList<ItemViewModel> GetAll()
        {
            var result = HttpContext.Session["items"] as List<ItemViewModel>;

            if (result == null)
            {
                result = new List<ItemViewModel>();

                for (int i = 1; i < 2001; i++)
                {
                    var item = new ItemViewModel() { Id = i, Name = "Item " + i.ToString() };
                    result.Add(item);
                }

                HttpContext.Session["items"] = result;
            }

            return result;
        }
    }
}
