using WCS.Core;
using WCS.WorkEngineering.Extensions;
using WCS.WorkEngineering.Protocol.SRM;
using WCS.WorkEngineering.Protocol.Station;
using WCS.WorkEngineering.Worlds;
namespace WCS.WorkEngineering.Systems
{
    /// 
    ///  设备信息写入接口
    /// 
    [BelongTo(typeof(MainWorld))]
    public class DeviceWriteSystem : ServiceSystem
    {
        /// 
        /// 所有的站台
        /// 
        private Dictionary Convs;
        private Dictionary Srms;
        /// 
        ///  构造函数
        /// 
        public DeviceWriteSystem()
        {
            Convs = Device.All.Where(v => v.HasProtocol()).Select(v => new Station(v, this.World)).ToDictionary(v => v.Entity.Code, v => v);
            Srms = Device.All.Where(v => v.HasProtocol()).Select(v => new SRM(v, this.World)).ToDictionary(v => v.Entity.Code, v => v);
        }
        protected override void Do(DeviceWriteInfo info)
        {
            Type? type = null;
            object? obj = null;
            switch (info.DeviceType)
            {
                case DeviceTypeEnum.SRM:
                    var srm = Srms[info.Code];
                    type = typeof(ISRM520).Assembly.GetTypes().Where(v => v.Name == info.Protocol).First();
                    obj = srm.Entity.Protocol(type, this.World);
                    break;
                case DeviceTypeEnum.DEV:
                    var conv = Convs[info.Code];
                    type = typeof(IStation523).Assembly.GetTypes().Where(v => v.Name == info.Protocol).First();
                    obj = conv.Entity.Protocol(type, this.World);
                    break;
                case DeviceTypeEnum.BCR:
                    break;
                case DeviceTypeEnum.RGV:
                    break;
            }
            var p = type.GetProperty(info.Property);
            if (p.PropertyType.IsEnum)
            {
                var value = Enum.Parse(p.PropertyType, info.Value);
                p.SetValue(obj, value);
            }
            else
            {
                var value = Convert.ChangeType(info.Value, p.PropertyType);
                p.SetValue(obj, value);
            }
        }
    }
    /// 
    /// 设备写入信息
    /// 
    public class DeviceWriteInfo
    {
        /// 
        ///  设备类型
        /// 
        public DeviceTypeEnum DeviceType { get; set; }
        /// 
        /// 设备号
        /// 
        public string Code { get; set; }
        /// 
        ///  协议
        /// 
        public string Protocol { get; set; }
        /// 
        /// 字段明
        /// 
        public string Property { get; set; }
        /// 
        ///  值
        /// 
        public string Value { get; set; }
    }
    /// 
    ///  设备类型接口
    /// 
    public enum DeviceTypeEnum
    {
        /// 
        ///  堆垛机
        /// 
        SRM = 1,
        /// 
        ///  输送线
        /// 
        DEV = 2,
        /// 
        ///  扫码器
        /// 
        BCR = 3,
        /// 
        /// RGV小车
        /// 
        RGV = 4,
    }
}