using System;
using System.Threading.Tasks;

namespace ASHermed.SinoInterface.Tools
{
    /// <summary>
    /// redis缓存扩展类
    /// </summary>
    public static class RedisHelperClientExtensions
    {
        /// <summary>
        /// 从缓存中获取值，如果值存在直接返回，不存在则执行委托
        /// </summary>
        /// <param name="redisHelper"></param>
        /// <param name="key"></param>
        /// <param name="expiry"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        public static async Task<TCacheObject> GetOrSetAsync<TCacheObject>(
            this RedisHelperClient redisHelper,
            string key,
            TimeSpan expiry,
            Func<Task<TCacheObject>> factory)
        {
            TCacheObject cacheObject;

            var result = await redisHelper.GetAsync<TCacheObject>(key);

            if (result == null)
            {
                cacheObject = await factory.Invoke();

                await redisHelper.StringSetAsync(key, cacheObject, expiry);
            }
            else
            {
                cacheObject = result;
            }

            return cacheObject;
        }

        /// <summary>
        /// 从缓存中获取值，如果值存在直接返回，不存在则执行委托
        /// </summary>
        /// <param name="redisHelper"></param>
        /// <param name="key"></param>
        /// <param name="expiry"></param>
        /// <param name="factory"></param>
        /// <returns></returns>
        public static TCacheObject GetOrSet<TCacheObject>(
            this RedisHelperClient redisHelper,
            string key,
            TimeSpan expiry,
            Func<TCacheObject> factory)
        {
            TCacheObject cacheObject;

            var result = redisHelper.Get<TCacheObject>(key);

            if (result == null)
            {
                cacheObject = factory.Invoke();

                redisHelper.StringSet(key, cacheObject, expiry);
            }
            else
            {
                cacheObject = result;
            }

            return cacheObject;
        }
    }
}