using System;
using System.Collections.Generic;
using System.Linq;
using RadTreeViewWithWCF.ServiceReference1;
using System.Collections.ObjectModel;

namespace RadTreeViewWithWCF
{
	public class HierarchicalDataSource : ObservableCollection<TableItem>
	{
		// This list holds all the items that come from the web service result
		private List<TableItem> unsortedList = new List<TableItem>();

		public HierarchicalDataSource()
		{
			// Create a new instance of the web service and get the data from the table
			Service1Client webService = new Service1Client();
			webService.GetTVSerieCompleted += new EventHandler<GetTVSerieCompletedEventArgs>(WebService_GetTableCompleted);
			webService.GetTVSerieAsync();
		}

		private void WebService_GetTableCompleted(object sender, GetTVSerieCompletedEventArgs e)
		{
			// transfer all the items from the result to the unsorted list
			foreach (FoxTVSery item in e.Result)
			{
				TableItem genericItem = new TableItem(item.NodeText, item.NodeID, item.ParentID);
				this.unsortedList.Add(genericItem);
			}

			// Get all the first level nodes. In our case it is only one - House M.D.
			var rootNodes = this.unsortedList.Where(x => x.ParentID == x.NodeID);

			// Foreach root node, get all its children and add the node to the HierarchicalDataSource.
			// see bellow how the FindChildren method works
			foreach (TableItem node in rootNodes)
			{
				this.FindChildren(node);
				this.Add(node);
			}
		}
		
		private void FindChildren(TableItem item)
		{
			// find all the children of the item
			var children = unsortedList.Where(x => x.ParentID == item.NodeID && x.NodeID != item.NodeID);

			// add the child to the item's children collection and call the FindChildren recursively, in case the child has children
			foreach (TableItem child in children)
			{
				item.Children.Add(child);
				FindChildren(child);
			}
		}
	}
}
