using System;
using System.Windows.Controls;
using System.Windows.Input;
using Telerik.Windows.Data;
using System.Windows;

namespace GroupPanelCheckBox
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class Window1 : Window
	{
		public static RoutedCommand ChangeCheckedStateCommand
		{
			get;
			set;
		}

		static Window1()
		{
			ChangeCheckedStateCommand = new RoutedCommand("ChangeCheckedState", typeof(Window1));
		}

		public Window1()
		{
			InitializeComponent();
			

			RadGridView1.ItemsSource = new Message[] { 
				new Message { Sender = "tom@hanna-barbera.com", Subject = "Cats are cool", Size = 100 },
				new Message { Sender = "jerry@hanna-barbera.com", Subject = "Mice are cool", Size = 100 },
				new Message { Sender = "spike@hanna-barbera.com", Subject = "Dogs are cool", Size = 100 }
			};

			this.CommandBindings.Add(new CommandBinding(Window1.ChangeCheckedStateCommand, this.DeleteExecuted, this.DeleteCanExecute));
		}

		public void DeleteCanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}

		public void DeleteExecuted(object sender, ExecutedRoutedEventArgs e)
		{
			GroupRecord group = (GroupRecord)e.Parameter;
			CheckBox checkBox = (CheckBox)e.OriginalSource;

			this.ChangeCheckedState(group, (bool)checkBox.IsChecked);
		}

		private void ChangeCheckedState(GroupRecord group, bool isChecked)
		{
			if (group == null)
				return;

			foreach (var item in group.Records)
			{
				ChangeCheckedState(item as DataRecord, isChecked);
				ChangeCheckedState(item as GroupRecord, isChecked);
			}
		}

		private void ChangeCheckedState(DataRecord record, bool isChecked)
		{
			if (record == null)
				return;

			Message message = (Message)record.Data;
			message.IsChecked = isChecked;
		}
	}
}
