using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace AsyncValidationWPFExample
{
	public class Person : INotifyPropertyChanged, IDataErrorInfo
	{
		#region INotifyPropertyChanged Members
		public event PropertyChangedEventHandler PropertyChanged;

		private void OnPropertyChanged(string propertyName)
		{
			if (this.PropertyChanged != null)
				this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}

		#endregion

		private string firstName;
		public string FirstName
		{
			get
			{
				return this.firstName;
			}
			set
			{
				if (this.firstName != value)
				{
					this.firstName = value;


					this.OnPropertyChanged("FirstName");
				}
			}
		}

		private string lastName;
		public string LastName
		{
			get
			{
				return this.lastName;
			}
			set
			{
				if (this.lastName != value)
				{
					this.lastName = value;
					this.OnPropertyChanged("LastName");
				}
			}
		}

		private int age;
		public int Age
		{
			get
			{
				return this.age;
			}
			set
			{
				if (this.age != value)
				{
					this.age = value;
					this.OnPropertyChanged("Age");
				}
			}
		}

		private DateTime birthDay;
		public DateTime BirthDay
		{
			get
			{
				return this.birthDay;
			}
			set
			{
				if (this.birthDay != value)
				{
					this.birthDay = value;
					this.OnPropertyChanged("BirthDay");
				}
			}
		}

		private readonly Dictionary<string, string> errors = new Dictionary<string, string>();

		public void ClearErrors()
		{
			this.errors.Clear();
		}

		public void SetError(string propertyName, string error)
		{
			string currentPropertyError;
			if (this.errors.TryGetValue(propertyName, out currentPropertyError))
			{
				this.errors.Remove(propertyName);
			}

			this.errors.Add(propertyName, error);
			this.OnPropertyChanged(propertyName);
		}

		public string GetError(string propertyName)
		{
			string result;
			if (this.errors.TryGetValue(propertyName, out result))
			{
				return result;
			}
			return null;
		}
	
		public string this[string columnName]
		{
			get
			{
				if (columnName == "FirstName")
				{
					// validation rule for FirstName - it cannot be null or empty
					if (string.IsNullOrEmpty(this.FirstName))
					{
						// error if validation fails
						return "Property cannot be null or empty";
					}

				}

				return this.GetError(columnName);
			}
		}

		public string Error
		{
			get
			{
				return null;
			}
		}
	}
}
