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 ticks = 0) where T : class
        {
            var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            var configurationBuilder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{environmentName}.json", true, reloadOnChange: true);
            var configuration = configurationBuilder.Build();
            ConfigManagerConf.SetConfiguration(configuration);
            var _cache = CacheManagerFactory.GetCacheManager();

            object cache = _cache.Get<T>(name);
            if (cache == null)
            {
                cache = getData();
                if (!string.IsNullOrEmpty(cache.ToString()))
                {
                    _cache.Add(name, cache);
                    if (ticks <= 0)
                    {
                        _cache.SetExpire(name, new TimeSpan(1, 0, 0, 0)); //设置一天缓存
                    }

                    else
                        _cache.SetExpire(name, new TimeSpan(ticks));
                }
                else
                    return default(T);
            }
            return (T)cache;

        }
    }
}
