using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Web;

namespace Qusion.WebApp.Areas.Qusion.Filters
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
        AllowMultiple = true)]
    public class EqualAttribute : ValidationAttribute
    {

        private string OtherProperty { get; set; }
        private new string ErrorMessage { get; set; }

        public EqualAttribute(string otherProperty, string errorMessage = null)
        {
            OtherProperty = otherProperty;
            ErrorMessage = errorMessage ?? String.Format("Not equal");
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            PropertyInfo property = validationContext.ObjectType.GetProperty(OtherProperty);

            if (property == null)
                return new ValidationResult(String.Format("Property {0} not found.", OtherProperty));

            object propertyValue = property.GetValue(validationContext.ObjectInstance, null);

            if (value != null)
                return !value.Equals(propertyValue) ? new ValidationResult(ErrorMessage) : null;
            return new ValidationResult(ErrorMessage);

        }
    }
}