using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudInfrastructure
{
    public static class MemoryCacheExtentions
    {
        private static readonly TimeSpan CacheOlescence = TimeSpan.FromMinutes(5);

        public static Task<IEnumerable<T>> GetOrCreateBasicAsync<T>(this IMemoryCache memoryCache, IAsbCloudDbContext dbContext, CancellationToken token)
            where T : class
        {
            var cacheTag = typeof(T).FullName;
            var cache = memoryCache.GetOrCreateAsync(cacheTag, async (cacheEntry) => {
                cacheEntry.AbsoluteExpirationRelativeToNow = CacheOlescence;
                cacheEntry.SlidingExpiration = CacheOlescence;

                var entities = await dbContext.Set<T>().ToArrayAsync(token);
                return entities.AsEnumerable();
            });
            return cache;
        }

        public static IEnumerable<T> GetOrCreateBasic<T>(this IMemoryCache memoryCache, IAsbCloudDbContext dbContext)
            where T : class
        {
            var cacheTag = typeof(T).FullName;
            var cache = memoryCache.GetOrCreate(cacheTag, cacheEntry => {
                cacheEntry.AbsoluteExpirationRelativeToNow = CacheOlescence;
                cacheEntry.SlidingExpiration = CacheOlescence;

                var entities = dbContext.Set<T>().ToArray();
                return entities.AsEnumerable();
            });
            return cache;
        }
    }
}