/*-------------------------------------------------------------------------
 * 功能描述：BimObjectUtil
 * 作者：xulisong
 * 创建时间： 2019/6/18 15:13:11
 * 版本号：v1.0
 *  -------------------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace JBIM.Common
{
    public static class BimObjectUtil
    {
        public static void AcceptRelation<T>(BimObject bimObject, string property,T value)
        {
            var propertyInfo=ParseProperty(bimObject, property);
            if (propertyInfo != null)
            {
                if (propertyInfo.PropertyType.IsInstanceOfType(value))
                {
                    propertyInfo.SetValue(bimObject, value);
                }
            }
        }
        /// <summary>
        /// 增加单关联信息
        /// </summary>
        /// <param name="bimObject"></param>
        /// <param name="property"></param>
        /// <param name="value"></param>
        public static void AcceptRelation(BimObject bimObject, string property, BimId value)
        {
            AcceptRelation<BimId>(bimObject, property, value);
        }
        /// <summary>
        /// 增加一对多关联信息
        /// </summary>
        /// <param name="bimObject"></param>
        /// <param name="property"></param>
        /// <param name="value"></param>
        public static void AcceptRelations(BimObject bimObject, string property,List<BimId> value)
        {
            AcceptRelation<List<BimId>>(bimObject, property, value);
        }
        private static PropertyInfo ParseProperty(BimObject bimObject,string pName)
        {
            var type = bimObject.GetType();
            string propertyName = pName;
            var key = type.FullName + "_" + propertyName;
            var propertyInfo = PropertyCache.GetProperty(key);
            if (propertyInfo == null)
            {
                //缓存解析出来的属性元数据，以便提高解析速度
                propertyInfo = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
                if(propertyInfo!=null)
                {
                    PropertyCache.SetProperty(key, propertyInfo);
                }
            }
            return propertyInfo;
        }
    }
}
