using Hotline.Caching.Interfaces;
using Hotline.Settings;
using XF.Domain.Cache;
using XF.Domain.Dependency;
using XF.Domain.Repository;

namespace Hotline.Caching.Services
{
    internal class TableAccessLevelCacheManager : ITableAccessLevelCacheManager, IScopeDependency
    {
        private const string TableAccessLevelCacheKey = "TableAccessLevel";
        private readonly ITypedCache<IReadOnlyList<TableAccessLevelCacheItem>> _cache;
        private readonly IRepository<TableAccessLevel> _repository;

        public TableAccessLevelCacheManager(ITypedCache<IReadOnlyList<TableAccessLevelCacheItem>> cache, IRepository<TableAccessLevel> repository)
        {
            _cache = cache;
            _repository = repository;
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public IReadOnlyList<TableAccessLevelCacheItem> QueryAll() => _cache.Get(TableAccessLevelCacheKey);

        /// <summary>
        /// 重载
        /// </summary>
        public void Reload()
        {
            var levels = _repository.QueryAsync(d => true).GetAwaiter().GetResult();
            var items = levels.Select(d => new TableAccessLevelCacheItem
            {
                RoleCode = d.RoleCode,
                TableName = d.TableName,
                AccessLevel = d.AccessLevel,
            }).ToList();
            //_cache.Remove(TableAccessLevelCacheKey);
            _cache.Set(TableAccessLevelCacheKey, items);
        }
    }
}
