using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Windows.Controls;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace ClosePopupOnApplyFilter
{
	/// <summary>
	/// A behavior that closes the filtering popup of a column when the Apply Filter 
	/// button is clicked.
	/// </summary>
	public class ClosePopupOnApplyFilterBehavior : Behavior<GridViewBoundColumnBase>
	{
		FilteringControl customFilteringControl;
		Button applyFilterButton;

		/// <summary>
		/// Called after the behavior is attached to an AssociatedObject.
		/// </summary>
		/// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks>
		protected override void OnAttached()
		{
			// This is the control that RadGridView uses internally if you 
			// don't specify a custom filtering control through the 
			// GridViewBoundColumnBase.FilteringControl property. 
			// We will create an instance of this default filtering control 
			// and use it as a "custom" filtering control in order to extend 
			// just a little bit with our custom logic. Everything else will
			// be the same.
			this.customFilteringControl = new FilteringControl(this.AssociatedObject);
			this.customFilteringControl.Loaded += this.OnFilteringControlLoaded;

			// Tell the column to use our new "custom" filtering control.
			// It will never now that this is the default one but spicied up a little.
			this.AssociatedObject.FilteringControl = customFilteringControl;
		}

		void OnFilteringControlLoaded(object sender, RoutedEventArgs e)
		{
			// When it loads and all of its children are alive find the "Filter" 
			// button which is the only button on the control.
			// You can find out what its name is from the FilteringControl template.
			this.applyFilterButton = this.customFilteringControl
				.ChildrenOfType<Button>()
				.Where(b => b.Name == "PART_ApplyFilterButton")
				.FirstOrDefault();

			if (this.applyFilterButton != null)
			{
				this.applyFilterButton.Click += this.OnApplyFilter;
			}
		}

		void OnApplyFilter(object sender, RoutedEventArgs e)
		{
			// And when clicked find the parent popup and close it.
			var popup = applyFilterButton.ParentOfType<System.Windows.Controls.Primitives.Popup>();
			if (popup != null)
			{
				popup.IsOpen = false;
			}
		}

		/// <summary>
		/// Called when the behavior is being detached from its AssociatedObject, 
		/// but before it has actually occurred.
		/// </summary>
		/// <remarks>Override this to unhook functionality from the AssociatedObject.</remarks>
		protected override void OnDetaching()
		{
			if (this.applyFilterButton != null)
			{
				this.applyFilterButton.Click -= this.OnApplyFilter;
			}

			this.customFilteringControl.Loaded -= this.OnFilteringControlLoaded;
		}
	}
}
