﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Albatross.MVVM.Validation {
	public class NotifyDataErrorValidation : INotifyDataErrorInfo {
		protected Dictionary<string, IEnumerable<ValidationResult>> _validations = new Dictionary<string, IEnumerable<ValidationResult>>();
		public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

		public bool HasErrors { get { return _validations.Count > 0; } }
		public IEnumerable GetErrors(string propertyName) {
			if (propertyName == null) { propertyName = string.Empty; }
			IEnumerable<ValidationResult> list;
			if (_validations.TryGetValue(propertyName, out list)) {
				return list;
			}
			return null;
		}
		protected void Validate(string property, params Func<ValidationResult>[] handles) {
			List<ValidationResult> list = new List<ValidationResult>();
			foreach (var handle in handles) {
				var result = handle();
				if (result != null) { list.Add(result); }
			}
			if (_validations.ContainsKey(property) && list.Count == 0) {
				_validations.Remove(property);
				RaiseErrorChanged(property);
			} else if (list.Count > 0) {
				_validations[property] = list;
				RaiseErrorChanged(property);
			}
		}
		public void RaiseErrorChanged(params string[] names) {
			var handle = ErrorsChanged;
			if (handle != null) {
				foreach (string name in names) {
					handle(this, new DataErrorsChangedEventArgs(name));
				}
			}
		}
	}
}
