namespace CommonLibrary.MVC
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Net;
    using System.Web.Mvc;

    public class IpAddressAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public IpAddressAttribute()
            : base(@"^([\d]{1,3}\.){3}[\d]{1,3}$")
        {
        }

        public override bool IsValid(object value)
        {
            if (!base.IsValid(value))
            {
                return false;
            }

            string ipValue = value as string;
            if (this.IsIpAddressValid(ipValue))
            {
                return true;
            }

            return false;
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format("'{0}'字段格式错误", name);
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            string fieldName = metadata.DisplayName;
            string errorMessage = string.Format("'{0}'字段格式错误", fieldName);
            const string pattern = @"^([\d]{1,3}\.){3}[\d]{1,3}$";

            ModelClientValidationRegexRule patternRule = new ModelClientValidationRegexRule(errorMessage, pattern);
            yield return patternRule;

            ModelClientValidationRule ipRule = new ModelClientValidationRule();
            ipRule.ValidationType = "ipformat";
            ipRule.ErrorMessage = string.Format("'{0}'字段值错误.", fieldName);

            yield return ipRule;
        }

        private bool IsIpAddressValid(string ipAddress)
        {
            IPAddress address;
            return !string.IsNullOrEmpty(ipAddress) && IPAddress.TryParse(ipAddress, out address);
        }
    }
}
