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

    public class MacAddressAttribute : RegularExpressionAttribute, IClientValidatable
    {
        private const string Macpattern = @"^([0-9A-Fa-f]{2}[:]){5}([0-9A-Fa-f]{2})$";

        public MacAddressAttribute()
            : base(Macpattern)
        {
        }

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

            string macValue = value as string;
            if (MacAddress.IsMacAddressValid(macValue,Macpattern))
            {
                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);

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

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

            yield return macRule;
        }
    }
}
