using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Telerik.Windows;
using Telerik.Windows.Controls.DragDrop;
using System.Collections;
using Telerik.Windows.Controls;

namespace SilverlightApplication1
{
	public partial class MainPage : UserControl
	{
		public MainPage()
		{
			InitializeComponent();

			this.treeView1.ItemsSource = new DataItems();
			this.treeView2.ItemsSource = new ObservableCollection<DataItem>();

			this.treeView2.AddHandler(RadDragAndDropManager.DropInfoEvent, new EventHandler<DragDropEventArgs>(OnDropInfo), true);
			this.treeView1.PreviewDragEnded += new Telerik.Windows.Controls.RadTreeViewDragEndedEventHandler(TreeView_PreviewDragEnded);
			this.treeView2.PreviewDragEnded += new Telerik.Windows.Controls.RadTreeViewDragEndedEventHandler(TreeView_PreviewDragEnded);
		}

		void TreeView_PreviewDragEnded(object sender, Telerik.Windows.Controls.RadTreeViewDragEndedEventArgs e)
		{
			e.Handled = true;
		}

		//DropInfo of RadTreeView2
		private void OnDropInfo(object sender, DragDropEventArgs e)
		{
			ICollection draggedItems = e.Options.Payload as ICollection;
			if (e.Options.Status == DragStatus.DropComplete)
			{
				var ass = draggedItems.Cast<DataItem>();
				System.Windows.Controls.ItemsControl dest = e.Options.Destination as System.Windows.Controls.ItemsControl;
				DataItem assunto = ass.First().CloneDataItem();
				(dest.ItemsSource as ObservableCollection<DataItem>).Add(assunto);
			}
		}
	}

	public static class MyExtensions
	{
		public static DataItem CloneDataItem(this DataItem originalItem)
		{
			DataItem clone = new DataItem();
			clone.Name = originalItem.Name;

			foreach (var item in originalItem.Children)
			{
				clone.Children.Add(CloneDataItem(item as DataItem));
			}

			return clone;
		}
	}


	public class DataItems : ObservableCollection<DataItem>
	{
		public DataItems()
		{
			for (int i = 0; i < 5; i++)
			{
				DataItem dataItem = new DataItem();
				dataItem.Name = string.Format("Item {0}", i);

				for (int j = 0; j < 5; j++)
				{
					DataItem subDataItem = new DataItem();
					subDataItem.Name = string.Format("Item {0}.{1}", i, j);
					dataItem.Children.Add(subDataItem);
				}

				this.Add(dataItem);
			}
		}
	}

	public class DataItem
	{
		public DataItem()
		{
			this.Children = new ObservableCollection<DataItem>();
		}
		public string Name { get; set; }
		public ObservableCollection<DataItem> Children { get; set; }
	}
}
