using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TreeView.Models;
using Telerik.Web.Mvc.UI;
using System.Collections;

namespace TreeView.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            NorthwindDataContext northwind = new NorthwindDataContext();

            return View(northwind.Employees.Where(e => e.ReportsTo == null));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult _AjaxLoading(TreeViewItem node)
        {
            NorthwindDataContext northwind = new NorthwindDataContext();

            int? parentId = !string.IsNullOrEmpty(node.Value) ? (int?)Convert.ToInt32(node.Value) : null;

            IEnumerable nodes = from item in northwind.Employees
                                where item.ReportsTo == parentId || (parentId == null && item.ReportsTo == null)
                                select new TreeViewItem
                                {
                                    Text = item.FirstName + " " + item.LastName,
                                    Value = item.EmployeeID.ToString(),
                                    LoadOnDemand = item.Employees.Count > 0,
                                    Enabled = true
                                };

            return new JsonResult { Data = nodes };
        }

        public ActionResult TestView(int id)
        {
            NorthwindDataContext northwind = new NorthwindDataContext();

            Employee emp = (from p in northwind.Employees
                            where p.EmployeeID == id
                            select p).FirstOrDefault();

            return View(emp);
        }

        public ActionResult CustomUpdate(Employee employee)
        {
            // Update employee

            return RedirectToAction("Index");
        }
    }
}