using System.Diagnostics;
using FreeRedis;
using JiShe.CollectBus.Common.Helpers;
using JiShe.CollectBus.FreeRedis.Options;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;

namespace JiShe.CollectBus.FreeRedis
{

    public class FreeRedisProvider : IFreeRedisProvider, ISingletonDependency
    {

        private readonly FreeRedisOptions _option;

        /// <summary>
        /// FreeRedis 
        /// </summary>
        public FreeRedisProvider(IOptions<FreeRedisOptions> options)
        {
            _option = options.Value;
            GetInstance();
        }

        public RedisClient Instance { get; set; } = new(string.Empty);

        /// <summary>
        /// 获取 FreeRedis 客户端
        /// </summary>
        /// <returns></returns>
        public IRedisClient GetInstance()
        {

            var connectionString = $"{_option.Configuration},defaultdatabase={_option.DefaultDB},MaxPoolSize={_option.MaxPoolSize}";
            Instance = new RedisClient(connectionString);
            Instance.Serialize = obj => BusJsonSerializer.Serialize(obj);
            Instance.Deserialize = (json, type) => BusJsonSerializer.Deserialize(json, type);
            Instance.Notice += (s, e) => Trace.WriteLine(e.Log); 
            return Instance;
        } 
    }
}