using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;
using System.Windows.Interactivity;

namespace AddNewRowAttachedBehavior
{
	public class AddNewRowBehavior : Behavior<RadGridView>
	{
		protected override void OnAttached()
		{
			base.OnAttached();
			this.AssociatedObject.LayoutUpdated += new EventHandler(AssociatedObject_LayoutUpdated);
		}

		void AssociatedObject_LayoutUpdated(object sender, EventArgs e)
		{
			this.AssociatedObject.LayoutUpdated -= new EventHandler(AssociatedObject_LayoutUpdated);
			AttachButton();
		}

		private void AttachButton()
		{
			Panel placeholder = InsertPlaceHolder();

			Button insertButton = new Button()
			{
				//To allow templating or styling a good idea would be to use a user control here and set properties trough XAML
				Content = "Insert new...",
				Height = 20,
				Width = 80,
				HorizontalAlignment = HorizontalAlignment.Left
			};

			placeholder.Children.Add(insertButton);
			insertButton.Click += new RoutedEventHandler(insertButton_Click);
		}

		void insertButton_Click(object sender, RoutedEventArgs e)
		{
			this.AssociatedObject.BeginInsert();
		}

		private Panel InsertPlaceHolder()
		{
			Border rootBorder = (Border) VisualTreeHelper.GetChild(this.AssociatedObject, 0);
			Grid rootGrid = (Grid) VisualTreeHelper.GetChild(rootBorder, 0);
			foreach (var child in rootGrid.Children)
			{
				child.SetValue(Grid.RowProperty, 1);
			}

			rootGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
			rootGrid.RowDefinitions.Add(new RowDefinition());

			StackPanel stackPanel = new StackPanel() 
				{ 
					Background = new SolidColorBrush(Colors.DarkGray),
					Height=20,
					HorizontalAlignment = HorizontalAlignment.Stretch };
			rootGrid.Children.Add(stackPanel);

			return stackPanel;
		}
	}
}
