using Microsoft.Extensions.Caching.Memory;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace HTCoreServiceApp.DataHandle
{
    public class CacheService
    {
        private readonly IMemoryCache _cache;
        private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();

        public CacheService(IMemoryCache cache)
        {
            _cache = cache;
        }

        public async Task<string> AddDataAsync(string key, string data)
        {
            //_lock.EnterReadLock();
            //try
            //{
            //    if (_cache.TryGetValue(key, out string cachedValue))
            //    {
            //        return cachedValue;
            //    }
            //}
            //finally
            //{
            //    _lock.ExitReadLock();
            //}

            // 数据不在缓存中，需要计算并添加到缓存
            //string newValue = await getDataAsync();

            _lock.EnterWriteLock();
            try
            {
                //// 再次检查缓存，以防在等待写锁时数据已被其他线程添加
                //if (!_cache.TryGetValue(key, out _))
                //{
                var cacheEntryOptions = new MemoryCacheEntryOptions()
                    .SetAbsoluteExpiration(TimeSpan.FromMinutes(1)); // 设置缓存1分钟后过期
                _cache.Set(key, data, cacheEntryOptions);
                //}
            }
            finally
            {
                _lock.ExitWriteLock();
            }

            return  "";
        }

        public async Task<string> GetDataFromDatabaseAsync(string key)
        {
            // 模拟从数据库异步获取数据
            //await Task.Delay(100); // 模拟异步操作
            //return $"Data for {key} from database";

            _lock.EnterReadLock();
            try
            {
                if (_cache.TryGetValue(key, out string cachedValue))
                {
                    return cachedValue;
                }
            }
            finally
            {
                _lock.ExitReadLock();
            }

            return "";
        }
    }
}
