using System;
using System.Reflection;
using Newtonsoft.Json.Serialization;

namespace IRaCIS.Core.API
{

    public class NullToEmptyStringValueProvider : IValueProvider
    {
        PropertyInfo _MemberInfo;
        public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
        {
            _MemberInfo = memberInfo;
        }
        public object GetValue(object target)
        {
            object result = _MemberInfo.GetValue(target);
            if (_MemberInfo.PropertyType == typeof(string) && result == null) result = "";
            else if (_MemberInfo.PropertyType == typeof(String[]) && result == null) result = new string[] { };
            //else if (_MemberInfo.PropertyType == typeof(Nullable<Int32>) && result == null) result = 0;
            else if (_MemberInfo.PropertyType == typeof(Nullable<Decimal>) && result == null) result = 0.00M;

            return result;
        }
        public void SetValue(object target, object value)
        {

            if(_MemberInfo.PropertyType == typeof(string))
            {
                //去掉前后空格
                _MemberInfo.SetValue(target, value==null?string.Empty: value.ToString()==string.Empty? value:value.ToString().Trim());
              
            }
            else
            {
                _MemberInfo.SetValue(target, value);
            }
          
        }
    }

}
