using BPA.ApolloClient;
using BPA.Message;
using BPASmartClient.Helper;
using BPASmartClient.Message;
using BPASmartClient.Model;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
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; }

        public MQTT_Account Mqtt_Account { get; set; }

        public UriConfig uriConfig { get; set; }

        public ObservableCollection<DeviceConfigModelJson> deviceConfigModelJsons { get; set; }

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

        public void Initialize()
        {
            var text = TextHelper.GetInstance.ReadTextInfo("StartShop", "DeviceConfig");
            string path = $"{LocaPath.GetInstance().GetDeviceConfigPath}{text}.json";
            if (File.Exists(path))
            {
                string JsonString = File.ReadAllText(path);
                deviceConfigModelJsons = JsonConvert.DeserializeObject<ObservableCollection<DeviceConfigModelJson>>(JsonString);
            }
            if (deviceConfigModelJsons?.Count > 0)
            {
                ClientId = int.Parse(deviceConfigModelJsons.ElementAt(0).ShopId);
            }
            //ClientId = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ClientId"]);
            apolloUri = System.Configuration.ConfigurationManager.AppSettings["ApolloUri"].ToString();
            apoid = System.Configuration.ConfigurationManager.AppSettings["AppId"].ToString();
            namespa = System.Configuration.ConfigurationManager.AppSettings["Namespaces"].ToString();
            InternetInfo.IsEnableTest = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["IsEnableTest"].ToString());
            InitDeviceModel();
            InitConfig();
        }

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

        /// <summary>
        /// 加载设备模型
        /// </summary>
        private void InitDeviceModel()
        {

        }

        public void InitConfig()
        {
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory());
            configurationBuilder.AddApolloConfiguration(p =>
            {
                p.AppId = "HostComputer";
                p.MetaServer = apolloUri;
                p.Namespaces = new List<string>() { "application", namespa };
            });

            IConfiguration config = configurationBuilder.Build();
            MQTT_Config = config.GetSection("BrokerHostSettings").Value.FromJSON<MQTT_Entity>();
            Mqtt_Account = config.GetSection("MqttAccount").Value.FromJSON<MQTT_Account>();
            uriConfig = config.GetSection("URL").Value.FromJSON<UriConfig>();
            if (uriConfig != null)
            {
                InternetInfo.OrderServer = uriConfig.OrderServiceUrl;
                InternetInfo.StockServer = uriConfig.StockServiceUrl;
                InternetInfo.BroadcastPubTopic = uriConfig.BroadcastPubTopic;
                InternetInfo.DataVApiAddress = uriConfig.DataVServiceUrl;
                InternetInfo.WebServiceUri = uriConfig.WebServiceUrl;
                ActionManage.GetInstance.Send("配置初始化完成Iot启动");
            }
        }

        public void Start()
        {
        }

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

        public class MQTT_Account
        {
            public string UserName { get; set; }
            public string Password { get; set; }
        }

        public class UriConfig
        {
            public string OrderServiceUrl { get; set; }
            public string StockServiceUrl { get; set; }
            public string DataVServiceUrl { get; set; }
            public string WebServiceUrl { get; set; }
            public string BroadcastPubTopic { get; set; }
        }
    }
}