using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Linq;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using TreeViewSelfReferenceWCFService.ServiceReference1;

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

		public HierarchicalDataSource()
		{
			//Create a new instance of the web service and get the data from the table
			MyServiceClient webService = new MyServiceClient();
			webService.GetMyDataCompleted += new EventHandler<GetMyDataCompletedEventArgs>(webService_GetMyDataCompleted);
			webService.GetMyDataAsync();
		}

		void webService_GetMyDataCompleted(object sender, GetMyDataCompletedEventArgs e)
		{
			//transfer all the items from the result to the unsorted list
			foreach (MyDataTable item in e.Result)
			{
				TableItem genericItem = new TableItem(item.Text, item.ID, item.ParentID);
				this.unsortedList.Add(genericItem);
			}

			//Get all the first level nodes
			var rootNodes = this.unsortedList.Where(x => x.ParentID == 0);

			//Foreach root node, get all its children and add the node to the HierarchicalDataSource
			foreach (TableItem node in rootNodes)
			{
				this.FindChildren(node);
				this.Add(node);
			}
		}
		private void FindChildren(TableItem item)
		{
			//find all item's children
			var children = unsortedList.Where(x => x.ParentID == item.NodeID);

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

	}
}
