using BPA.ApolloClient;
using BPA.Message;
using BPASmartClient.Model;
using Microsoft.Extensions.Configuration;
using System.Xml.Linq;
using System.Xml.XPath;

namespace BPASmartClient.Business
{
    /// <summary>
    /// 配置管理器
    /// </summary>
    public class ConfigMgr : IPlugin
    {
        /// <summary>
        /// 门店ID
        /// </summary>
        public int ClientId { get; set; }
        /// <summary>
        /// MQTT Broker
        /// </summary>
        public MQTT_Entity MQTT_Config { get; set; }

        //Apollo地址
        private string apolloUri;
        //设备集合
        private List<DeviceConfig> deviceConfigs;
        public void Dispose()
        {
        }

        public void Initialize()
        {
            ClientId = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ClientId"]);
            apolloUri = System.Configuration.ConfigurationManager.AppSettings["ApolloUri"].ToString();
            InternetInfo.OrderServer= System.Configuration.ConfigurationManager.AppSettings["OrderServiceUri"].ToString(); 
            InternetInfo.StockServer= System.Configuration.ConfigurationManager.AppSettings["StockServiceUri"].ToString();

            InitDeviceModel();
            InitMQTT();
        }

        public List<DeviceConfig> GetDeviceConfigs()
        {
            if (null == deviceConfigs)
                InitDeviceModel();
            return deviceConfigs;
        }

        /// <summary>
        /// 加载设备模型
        /// </summary>
        private void InitDeviceModel()
        {
            deviceConfigs = new List<DeviceConfig>();
            var devicePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DeviceInfo.xml");
            var xdoc = XDocument.Load(devicePath);
            var devices = xdoc.XPathSelectElements("//Device");
            foreach (var device in devices)
            {
                DeviceConfig deviceConfig = new DeviceConfig();
                deviceConfig.Name = device.Attribute("Name").Value;
                deviceConfig.Module = device.Attribute("Module").Value;
                deviceConfig.DeviceId =int.Parse(device.Attribute("DeviceId").Value);

                foreach (var peripheralEl in device.XPathSelectElements("//Peripheral"))
                {
                    BPASmartClient.Model.Peripheral peripheral = new BPASmartClient.Model.Peripheral();
                    peripheral.Module = peripheralEl.Attribute("Module").Value;
                    foreach (XElement parameter in peripheralEl.Element("Parameters").Elements())
                    {
                        peripheral.Parameters.Add(parameter.Name.LocalName, parameter.Value);
                    }
                    deviceConfig.Peripherals.Add(peripheral);
                }
                deviceConfigs.Add(deviceConfig);
            }
        }

        /// <summary>
        /// 加载MQTT配置
        /// </summary>
        private void InitMQTT()
        {

            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory());
            configurationBuilder.AddApolloConfiguration(p =>
                {
                    p.AppId = "dev1_order";
                    p.MetaServer = apolloUri;
                    p.Namespaces = new List<string>() { "DEV.Config" };
                });
            IConfiguration config = configurationBuilder.Build();
            var mqttBroker = config.GetSection("BrokerHostSettings");
            MQTT_Config = mqttBroker.Value.FromJSON<MQTT_Entity>();
        }

        public class MQTT_Entity
        {
            public string Host { get; set; }
            public int Port { get; set; }
        }
    }
}