using Bailun.ServiceFabric.Extension;
using Bailun.ServiceFabric.Redis;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace AutoTurnOver.Utility
{
    public class RedisHelper
    {
        public static T Get<T>(string name, Func<T> getData, int minutes = 0) where T : class
        {
            name = (name + "v_aims_v1");


            string caheStr = RedisClient.redisClient.GetStringKey(name);


            T cache = default(T);
            if (!string.IsNullOrWhiteSpace(caheStr)) cache = caheStr.ToObj<T>();

            if (cache == null)
            {
                cache = getData();
                if (cache is string)
                {
                    if (!string.IsNullOrEmpty(cache.ToString()))
                    {
                        if (minutes <= 0)
                        {
                            RedisClient.redisClient.SetStringKey(name, cache.ToString(), (DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")) - DateTime.Now));

                        }
                        else
                        {
                            RedisClient.redisClient.SetStringKey(name, cache.ToString(), new TimeSpan(0, 0, minutes, 0));
                        }

                    }
                    else
                        return default(T);
                }
                else
                {
                    if (cache != null)
                    {
                        if (minutes <= 0)
                            RedisClient.redisClient.SetStringKey(name, cache.ToJson(), (DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 23:59:59")) - DateTime.Now));
                        else
                            RedisClient.redisClient.SetStringKey(name, cache.ToJson(), new TimeSpan(0, 0, minutes, 0));
                    }
                    else
                        return default(T);
                }
            }
            return cache;

        }


    }
}
