using System;
using System.Windows;
using System.Linq;
using System.Windows.Interactivity;
using System.Collections.ObjectModel;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;

namespace GroupColumnHeaders_WPF
{
	class ColumnGroupsBehavior : Behavior<RadGridView>
	{
		public ColumnGroupsBehavior()
		{
			this.CommonHeaders = new ObservableCollection<CommonHeader>();
		}

		protected override void OnAttached()
		{
			base.OnAttached();
			this.AssociatedObject.DataLoaded += new EventHandler<EventArgs>(AssociatedObject_DataLoaded);
			
			//this.AssociatedObject.ShowGroupPanel = false;
			this.AssociatedObject.CanUserFreezeColumns = false;
			this.AssociatedObject.CanUserReorderColumns = false;
		}

		void AssociatedObject_DataLoaded(object sender, EventArgs e)
		{
			PlaceSecondaryHeader();
		}

		private void PlaceSecondaryHeader()
		{
			SecondaryHeader secondaryHeader = new SecondaryHeader();
			secondaryHeader.ParentGridView = this.AssociatedObject;
			var grid = this.AssociatedObject.ChildrenOfType<System.Windows.Controls.Grid>().Where(c => c.Name == "HierrarchyBackground").FirstOrDefault();
			var indentPresenter = this.AssociatedObject.ChildrenOfType<Telerik.Windows.Controls.GridView.IndentPresenter>().Where(c => c.Name == "PART_SpecialIndentPresenter").FirstOrDefault();			
			var indentLevel = this.AssociatedObject.GroupCount;

			if (indentPresenter != null)
			{
				((IndentPresenter)indentPresenter).Visibility = Visibility.Visible;
				((IndentPresenter)indentPresenter).IndentLevel = indentLevel;

			}
			
			
			grid.Children.Add(secondaryHeader);
			secondaryHeader.SetValue(System.Windows.Controls.Grid.RowProperty, 1);
			secondaryHeader.CommonHeaders = this.CommonHeaders;
		}

		public ObservableCollection<CommonHeader> CommonHeaders
		{
			get;
			internal set;
		}
	}
}

