using BPASmartClient.Device;
using BPASmartClient.Helper;
using BPASmartClient.Peripheral;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.Business
{
    /// <summary>
    /// 设备管理器，统一管理所有设备资源
    /// </summary>
    public class DeviceMgr : IPlugin
    {
        //设备集合
        private List<IDevice> devices = new List<IDevice>();

        public void Dispose()
        {
        }

        public void Initialize()
        {
            LoadDevice();
        }

        public List<IDevice> GetDevices()
        {
            return devices;
        }

        /// <summary>
        /// 设备加载
        /// </summary>
        private void LoadDevice()
        {
            var devices = Plugin.GetInstance().GetPlugin<ConfigMgr>().GetDeviceConfigs();
            foreach (var device in devices)
            {
                var deviceTemp = Assembly.Load(device.Module.Substring(0, device.Module.LastIndexOf('.'))).CreateInstance(device.Module) as IDevice;
                deviceTemp.Name = device.Name;
                deviceTemp.DeviceId = device.DeviceId;

                List<IPeripheral> peripherals = new List<IPeripheral>();
                foreach (var peripheral in device.Peripherals)
                {
                    var peripheralTemp = Assembly.Load(peripheral.Module.Substring(0, peripheral.Module.LastIndexOf('.'))).CreateInstance(peripheral.Module) as IPeripheral;
                    foreach (var pars in peripheral.Parameters)
                    {
                        peripheralTemp.GetType().GetProperty(pars.Key).SetValue(peripheralTemp, Convert.ChangeType(pars.Value, peripheralTemp.GetType().GetProperty(pars.Key).PropertyType));
                    }
                    peripherals.Add(peripheralTemp);
                }
                deviceTemp.Initliaze(peripherals);
                this.devices.Add(deviceTemp);
            }
        }



        public void StartService()
        {
            this.devices.ForEach(device => device.StartMain());
        }

        public void StopService()
        {
            this.devices.ForEach(device => device.Stop());
        }
    }
}
