using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using xVal.ServerSide;

namespace Wierszowki.Services
{
    internal static class DataAnnotationsValidationRunner
    {
        public static IEnumerable<ErrorInfo> GetErrors(object instance)
        {   
            List<ErrorInfo> errors = new List<ErrorInfo>();

	        IEnumerable<PropertyDescriptor> properties = TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>();
	        foreach (PropertyDescriptor prop in properties) {
	            IEnumerable<ValidationAttribute> attributes = prop.Attributes.OfType<ValidationAttribute>();

                int empty = 2;
                object pom = prop.GetValue(instance);
                if (pom != null)
                {
                    object typek = pom.GetType();
                    if (pom.GetType().Name == "Int32")
                    {
                        empty = Convert.ToInt32(pom);
                    }
                }                                
                foreach (ValidationAttribute attribute in attributes) {
	                if (!attribute.IsValid(prop.GetValue(instance)) || empty == 0) {
	                    errors.Add(new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance));
	                }
	            }
	        }
	        return errors;
            /* return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                   from attribute in prop.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(prop.GetValue(instance))
                   select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
            */
        }
    }
}