using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using System.Web.Query.Dynamic;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Expressions;
using Telerik.Web.Mvc.Extensions;
using Telerik.Web.Mvc.UI;
using TelerikMvcApplication1.Models;

namespace TelerikMvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [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 employee in northwind.Employees
                                where employee.ReportsTo == parentId || (parentId == null && employee.ReportsTo == null)
                                select TreeViewItemFrom(employee);

            return new JsonResult { Data = nodes };
        }

        private TreeViewItem TreeViewItemFrom(Employee employee)
        {
            return new TreeViewItem
                                {
                                    Text = employee.FirstName + " " + employee.LastName + "<span class='data'>" + GetEmployeeColor(employee) + "</span>",
                                    Value = employee.EmployeeID.ToString(),
                                    LoadOnDemand = employee.Employees.Count > 0,
                                    Enabled = true,
                                    Encoded = false
                                };
        }

        public string GetEmployeeColor(Employee employee)
        {
            var rand = new Random(employee.ReportsTo.HasValue ? employee.ReportsTo.Value : 0);

            return rand.Next(0, 255).ToString("X2") + rand.Next(0, 255).ToString("X2") + rand.Next(0, 255).ToString("X2");
        }

    }
}
