using System.Text.RegularExpressions;
using JiShe.CollectBus.Common;
using JiShe.CollectBus.Common.Consts;
using JiShe.CollectBus.FreeRedis;
using JiShe.CollectBus.IotSystems.Protocols;
using JiShe.CollectBus.Protocol.Interfaces;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Volo.Abp;
using Volo.Abp.DependencyInjection;

namespace JiShe.CollectBus.Protocol.Services
{
    public class ProtocolService : IProtocolService, ISingletonDependency
    {
        private readonly IFreeRedisProvider _freeRedisProvider;
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<ProtocolService> _logger;
        private readonly ServerApplicationOptions _serverApplicationOptions;

        public ProtocolService(IFreeRedisProvider freeRedisProvider, IServiceProvider serviceProvider, ILogger<ProtocolService> logger,IOptions<ServerApplicationOptions> serverApplicationOptions)
        {
            _freeRedisProvider = freeRedisProvider;
            _serviceProvider = serviceProvider;
            _logger= logger;
            _serverApplicationOptions = serverApplicationOptions.Value;
        }

        /// <summary>
        /// 通过仪器设备型号获取协议信息
        /// </summary>
        /// <param name="deviceCode"></param>
        /// <param name="isSpecial"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task<ProtocolInfo> FirstOrDefaultByDeviceAsync(string deviceCode, bool isSpecial = false)
        {
            var protocols = await _freeRedisProvider.Instance.HGetAllAsync<ProtocolInfo>(RedisConst.ProtocolKey);
            var keyValuePair = protocols.FirstOrDefault(a => ContainsExactPartRegex(deviceCode, a.Value.RegularExpression));
            if (!keyValuePair.Key.IsNullOrWhiteSpace() || keyValuePair.Value != null) return keyValuePair.Value;
            if (isSpecial) throw new UserFriendlyException("The device protocol plugin does not exist!", ExceptionCode.NotFound);
            var hasStandardProtocolPlugin = protocols.TryGetValue(_serverApplicationOptions.DefaultProtocolPlugin, out var protocolInfo);
            if (!hasStandardProtocolPlugin) throw new UserFriendlyException("Standard protocol plugin does not exist!", ExceptionCode.NotFound);
            return protocolInfo;
        }

        /// <summary>
        /// 获取协议池服务
        /// </summary>
        /// <param name="deviceCode"></param>
        /// <param name="isSpecial"></param>
        /// <returns></returns>
        public async Task<IProtocolPlugin?> GetProtocolServiceAsync(string deviceCode, bool isSpecial = false)
        {
            try
            {
                //todo 必须添加本地内存缓存，然后是否需走个redis订阅？？？？
                ProtocolInfo protocolInfo= await FirstOrDefaultByDeviceAsync(deviceCode, isSpecial);
               if(protocolInfo==null)
                     return null;
               return _serviceProvider.GetKeyedService<IProtocolPlugin>(protocolInfo.Name);
            }
            catch (Exception ex) 
            {
                _logger.LogError(ex, "获取协议失败");
                return null;
            }
        }

        private static bool ContainsExactPartRegex(string searchPattern, string fullString)
        {
            // 构建正则表达式 - 匹配以逗号或开头为边界，以逗号或结尾为边界的部分
            var pattern = $"(^|,)\\s*{Regex.Escape(searchPattern)}\\s*(,|$)";
            return Regex.IsMatch(fullString, pattern, RegexOptions.IgnoreCase);
        }
    }
}
