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

namespace CustomFilteringControl_DateRange
{
	public partial class MyCustomFilteringControl : UserControl, IFilteringControl
	{		
		private GridViewDataColumn column;
		private CompositeFilterDescriptor compositeFilterDescriptor;
		private List<int> Days = new List<int>() { 30, 75, 90 };


		public MyCustomFilteringControl()
		{
			InitializeComponent();
		}

		#region IFilteringControl Members

		/// <summary>
		/// Gets or sets a value indicating whether the filtering is active.
		/// </summary>
		public bool IsActive
		{
			get
			{
				return (bool)GetValue(IsActiveProperty);
			}
			set
			{
				SetValue(IsActiveProperty, value);
			}
		}

		/// <summary>
		/// Identifies the <see cref="IsActive"/> dependency property.
		/// </summary>
		public static readonly DependencyProperty IsActiveProperty =
		DependencyProperty.Register(
			"IsActive",
			typeof(bool),
			typeof(MyCustomFilteringControl),
			new System.Windows.PropertyMetadata(false));

		public void Prepare(Telerik.Windows.Controls.GridViewBoundColumnBase column)
		{
			this.compositeFilterDescriptor = new CompositeFilterDescriptor() { LogicalOperator = FilterCompositionLogicalOperator.Or };
			this.column = column as GridViewDataColumn;
			this.listBoxDistinctValues.ItemsSource = this.Days;
			this.column.DataControl.FilterDescriptors.Add(compositeFilterDescriptor);
		}

		#endregion

		private void listBoxDistinctValues_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
		{
			compositeFilterDescriptor.FilterDescriptors.Clear();
            
			foreach (var item in this.listBoxDistinctValues.SelectedItems)
			{
				compositeFilterDescriptor.FilterDescriptors.Add(new FilterDescriptor(this.column.DataMemberBinding.Path.Path, FilterOperator.IsGreaterThanOrEqualTo, DateTime.Today.AddDays(-(int)item)));   //this.StartingDate - new TimeSpan((int)item,0,0,0)));
			}

			if (this.compositeFilterDescriptor.FilterDescriptors.Count > 0)
				this.SetValue(IsActiveProperty, true);
			else
				this.SetValue(IsActiveProperty, false);
		}

		private void OnClear(object sender, RoutedEventArgs e)
		{
			if (this.column.DataControl.FilterDescriptors.Contains(this.compositeFilterDescriptor))
			{
				this.column.DataControl.FilterDescriptors.Remove(this.compositeFilterDescriptor);
			}
			this.listBoxDistinctValues.SelectedItems.Clear();
			this.IsActive = false;
		}
	}
}   

