using FreeRedis;

namespace ServiceCenter.Extensions
{
    public static class RedisExtension
    {
        /// <summary>
        /// 检查Redis中是否有对应key且value不为空
        /// </summary>
        /// <param name="redisClient">redis连接</param>
        /// <param name="key">要检查的Key</param>
        /// <returns>
        /// 1.key不存在,创建这个key value默认为三个空格符。返回null
        /// 2.key存在单value为空 返回null
        /// 3.key存在value不为空 返回获取到的值
        /// </returns>
        public static string? Check(this RedisClient redisClient, string key)
        {
            var result = redisClient.Get(key);
            if (!string.IsNullOrEmpty(result)) return result;
            redisClient.Set(key, "   ");
            Console.WriteLine($"无{key},创建并写入默认值:   ");
            return null;
        }

        /// <summary>
        /// 检查Redis中是否有对应key且value不为空
        /// </summary>
        /// <param name="redisClient">redis连接</param>
        /// <param name="key">要检查的Key</param>
        /// <param name="defaults">创建key是写入的默认值</param>
        /// <returns>
        /// 1.key不存在,创建这个key 并写入传入的默认值。返回默认值
        /// 2.key存在单value为空 返回null
        /// 3.key存在value不为空 返回获取到的值
        /// </returns>
        public static string? Check(this RedisClient redisClient, string key, string defaults)
        {
            var result = redisClient.Get(key);
            if (!string.IsNullOrEmpty(result)) return result;
            redisClient.Set(key, defaults);
            Console.WriteLine($"无{key},创建并写入默认值:{defaults}");
            return defaults;
        }
    }
}
