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

namespace AsyncValidationWPFExample
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		ObservableCollection<Person> data;

		public MainWindow()
		{
			InitializeComponent();

			this.data = this.CreatePersonsDataSource(3);
			this.radGridView.ItemsSource = this.data;
			this.radGridView.RowValidating += new EventHandler<GridViewRowValidatingEventArgs>(radGridView_RowValidating);

			this.mybutton.Click += new RoutedEventHandler(mybutton_Click);
		}

		void mybutton_Click(object sender, RoutedEventArgs e)
		{
			var last = this.data.Last();

			Person clonedPerson = new Person();
			clonedPerson.Age = last.Age;
			clonedPerson.BirthDay = last.BirthDay;
			clonedPerson.FirstName = last.FirstName;
			clonedPerson.LastName = last.LastName;

			this.data.Add(clonedPerson);

			this.Dispatcher.BeginInvoke(new Action(() => this.ValidateNewPerson(clonedPerson)), 
				System.Windows.Threading.DispatcherPriority.ApplicationIdle ,null);
		}

		private void ValidateNewPerson(Person newPerson)
		{
			var row = this.radGridView.ItemContainerGenerator.ContainerFromItem(newPerson) as GridViewRow;
			row.BeginEdit();
			this.Dispatcher.BeginInvoke(new Action(() => row.CommitEdit()),  System.Windows.Threading.DispatcherPriority.ApplicationIdle, null);
		}

		void radGridView_RowValidating(object sender, GridViewRowValidatingEventArgs e)
		{
			var persontoValidate = e.Row.Item as Person;

			if (persontoValidate.FirstName != "person")
			{
				e.IsValid = false;
			}
		}

		private void radGridView_BeginningEdit(object sender, GridViewBeginningEditRoutedEventArgs e)
		{
			
		}

		private void radGridView_RowEditEnded(object sender, GridViewRowEditEndedEventArgs e)
		{
			
		}

		private ObservableCollection<Person> CreatePersonsDataSource(int count)
		{
			ObservableCollection<Person> persons = new ObservableCollection<Person>();
			for (int i = 0; i < count; i++)
			{
				persons.Add(new Person
				{
					FirstName = "John " + i,
					LastName = "Doe " + i,
					Age = i,
					BirthDay = DateTime.Today
				});
			}

			return persons;
		}
	}
}
