using MECF.Framework.Common.CommonData;
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading.Tasks;

namespace Aitex.Core.Common.DeviceData.IoDevice.Base
{
    [Serializable]
    [DataContract]
    public abstract class XDataBase : NotifiableItem, IDeviceData
    {
        /// <summary>
        /// 更新当前对象的属性。
        /// </summary>
        /// <param name="data"></param>
        public void Update(IDeviceData data)
        {
            if (data == null)
                return;

            var targetProps = GetType().GetProperties()
                .Where(prop => Attribute.IsDefined((MemberInfo)prop, typeof(DataMemberAttribute)));

            var sourceProps = data.GetType().GetProperties()
                .Where(prop => Attribute.IsDefined((MemberInfo)prop, typeof(DataMemberAttribute)));

            Parallel.ForEach(targetProps, pi =>
            {
                var srcPi = sourceProps.FirstOrDefault(x => x.Name == pi.Name);
                if (srcPi == null)
                    return;

                pi.SetValue(this, srcPi.GetValue(data));
            });
        }
    }
}
