using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace Qusion.WebApp.Areas.cms.Filters
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,
        AllowMultiple = true)]
    public class RequiredIfAttribute : ValidationAttribute
    {
        public RequiredIfAttribute(string otherProperty, object condition, string errorMessage = null)
        {
            OtherProperty = otherProperty;
            Condition = condition;
            ErrorMessage = errorMessage;
        }

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

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            PropertyInfo property = validationContext.ObjectType.GetProperty(OtherProperty);
            if (property == null)
            {
                return string.IsNullOrEmpty(ErrorMessage) ? 
                    new ValidationResult(String.Format("Property {0} not found.", OtherProperty)) 
                    : new ValidationResult(ErrorMessage);
            }

            object propertyValue = property.GetValue(validationContext.ObjectInstance, null);
            bool conditionIsMet = Equals(propertyValue, Condition);

            if (!string.IsNullOrEmpty(ErrorMessage))
                base.ErrorMessage = ErrorMessage;

            return conditionIsMet && value == null ? new ValidationResult(ErrorMessage) : null;
        }
    }
}