﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Reflection;
using System.Globalization;


namespace EzFramework.Mvc
{
    /// <summary>
    /// 值相等验证特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class CompareToAttribute : ValidationAttribute, IClientValidatable
    {
        private string propertyName;
        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="propertyName"></param>
        public CompareToAttribute(string propertyName)
        {
            this.propertyName = propertyName;
        }

        /// <summary>
        /// 是否通过验证
        /// </summary>
        /// <param name="value">输入值</param>
        /// <param name="validationContext">验证上下文</param>
        /// <returns></returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(propertyName);
            if (otherPropertyInfo == null)
            {
                return new ValidationResult("要验证的属性不存在！");
            }
            object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
            if (!Equals(value, otherPropertyValue))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
            return null;
        }
        /// <summary>
        /// 格式化客户端数据验证属性
        /// </summary>
        /// <param name="property">当前属性</param>
        /// <returns></returns>
        public static string FormatPropertyForClientValidation(string property)
        {
            if (property == null)
            {
                throw new ArgumentException("验证参数不存在");
            }
            return "*." + property;
        }
        /// <summary>
        /// 获取客户端验证规则
        /// </summary>
        /// <param name="metadata">数据模型元数据</param>
        /// <param name="context">当前控制上下文</param>
        /// <returns></returns>
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
                yield return new ModelClientValidationEqualToRule(
                    string.IsNullOrEmpty(ErrorMessage)?
                    String.Format(CultureInfo.CurrentCulture, Resources.resource.SYS_Val_NotEqal, metadata.DisplayName) :
                    ErrorMessage, FormatPropertyForClientValidation(propertyName)
                    );
        }

    }
}
