using System.Windows.Controls;
using System.Linq;
using System.Windows;
using Telerik.Windows.Controls;
using System.Collections.Generic;
using Telerik.Windows.Controls.GridView;
using System.Windows.Data;

namespace GroupColumnHeaders_WPF
{
	/// <summary>
	/// Interaction logic for SecondaryHeader.xaml
	/// </summary>
	public partial class SecondaryHeader : UserControl
	{
		public SecondaryHeader()
		{
			InitializeComponent();

			this.Loaded += new RoutedEventHandler(SecondaryHeader_Loaded);			
		}

		public RadGridView ParentGridView { get; set; }

		public IList<CommonHeader> CommonHeaders
		{
			get;
			internal set;
		}
		
		void SecondaryHeader_Loaded(object sender, RoutedEventArgs e)
		{
			GridViewHeaderRow headerRow = this.ParentGridView.ChildrenOfType<GridViewHeaderRow>().FirstOrDefault();
			var scroller = ParentGridView.ChildrenOfType<GridViewScrollViewer>().FirstOrDefault();
			scroller.ScrollChanged += new ScrollChangedEventHandler(scroller_ScrollChanged);

			BindToColumns();

			PlaceCommonHeaders();

			this.SecondaryHeadersGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
		}

		private void BindToColumns()
		{
			for (int i = 0; i < ParentGridView.Columns.Count; i++)
			{
				ColumnDefinition columndefinition = new ColumnDefinition() { Width = GridLength.Auto };
				this.SecondaryHeadersGrid.ColumnDefinitions.Add(columndefinition);
				Border border = new Border();
				border.SetValue(Grid.ColumnProperty, i);
				this.SecondaryHeadersGrid.Children.Add(border);
				border.SetBinding(Border.WidthProperty, new Binding("ActualWidth") { Source = ParentGridView.Columns[i] });
			}
		}

		private void PlaceCommonHeaders()
		{
			if (this.CommonHeaders.Count > 0 && this.CommonHeaders[0].Parent != null)
				return;

			foreach (var commonHeader in this.CommonHeaders)
			{
				commonHeader.SetValue(Grid.ColumnSpanProperty, commonHeader.ColumnSpan);
				commonHeader.SetValue(Grid.ColumnProperty, commonHeader.StartColumnIndex);
				this.SecondaryHeadersGrid.Children.Add(commonHeader);
			}
			
			CommonHeader lastEmptyHeader = new CommonHeader();
			lastEmptyHeader.SetValue(Grid.ColumnProperty, this.SecondaryHeadersGrid.ColumnDefinitions.Count);
			this.SecondaryHeadersGrid.Children.Add(lastEmptyHeader);

		}

		void scroller_ScrollChanged(object sender, ScrollChangedEventArgs e)
		{
			this.ScrollViewer.ScrollToHorizontalOffset(e.HorizontalOffset);
		}
	}
}
