using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using SlnMesnac.Config;
using SlnMesnac.Rfid.Factory;

namespace SlnMesnac.Rfid
{
    public class RfidPool
    {
        private readonly ILogger<RfidPool> _logger;
        private readonly RflyFactory _rflyFactory;
        private readonly AppConfig _appConfig;
        
        private Dictionary<string, RfidAbsractFactory> keyValuePairs = new Dictionary<string, RfidAbsractFactory>();

        public RfidPool(RflyFactory rflyFactory,ILogger<RfidPool> logger,AppConfig appConfig)
        {
            _rflyFactory = rflyFactory;
            _logger = logger;
            _appConfig = appConfig;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            
            if (_appConfig.rfidConfig != null)
            {
                foreach (var item in _appConfig.rfidConfig)
                {
                    if (item.isFlage)
                    {
                        try
                        {
                            RfidAbsractFactory absractFactory = _rflyFactory;
                            absractFactory.Connect(item.equipIp, item.equipPort);
                            _logger.LogInformation($"RFID：{item.equipIp}:{item.equipPort};连接成功，时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                            var key = item.equipKey;
                            if (!keyValuePairs.ContainsKey(key))
                            {
                                keyValuePairs.Add(key, absractFactory);
                            }
                            else
                            {
                                keyValuePairs[key] = absractFactory;
                            }
                        }
                        catch (Exception e)
                        {
                            _logger.LogError($"RFID设备:{item.equipKey}初始化异常:{e.Message}");
                        }
                    }
                }
            }
            else
            {
                _logger.LogInformation("PLC配置信息为空");
            }
        }
        
        /// <summary>
        /// 获取RFID设备
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public RfidAbsractFactory GetRfidByKey(string key)
        {
            try
            {
                return keyValuePairs[key];
            }
            catch (Exception e)
            {
                throw new ArgumentException($"根据RFID Key获取连接信息异常:{e.Message}"); ;
            }
        }

        /// <summary>
        /// 获取所有PLC信息
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, RfidAbsractFactory> GetAll()
        {
            return keyValuePairs;
        }
    }
}