using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using DataAccess.Domain.Entities;
using DataAccess.NHDal;
using DataAccess.Repository.Query;

using Telerik.Web.Mvc.UI;

namespace TelerikTreeTest.Controllers {
	public class HomeController : Controller {
		private NHibernateRepository<Category, int?> categoryRepository;

		public HomeController() {
			categoryRepository = new NHibernateRepository<Category, int?>();
		}

		public ActionResult Index() {
			IQueryable<Category> categories = categoryRepository.GetList(new CategoryByParentIdQuery(null))
				.OrderBy(c => c.Name);
			return View(categories.AsEnumerable());
		}

		[HttpPost]
		public ActionResult CategoryAjaxLoading(TreeViewItem node) {
			int? parentId = !string.IsNullOrEmpty(node.Value) ? (int?)Convert.ToInt32(node.Value) : null;

			IQueryable<Category> categories = categoryRepository.GetList(new CategoryByParentIdQuery(parentId))
				.OrderBy(c => c.Name);

			List<TreeViewItem> nodes = new List<TreeViewItem>();

			foreach (Category category in categories) {
				nodes.Add(new TreeViewItem()
				{
					Text = category.Name,
					Value = category.Id.Value.ToString(),
					LoadOnDemand = category.ChildCategory.Count() > 0
				});
			}

			return new JsonResult
			{
				Data = nodes
			};
		}
	}
}
