using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hotline.Caches;
using Hotline.Settings;
using XF.Domain.Cache;
using XF.Domain.Dependency;

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

        public TableAccessLevelCacheManager(ITypedCache<IReadOnlyList<TableAccessLevelCacheItem>> cache, ITableAccessLevelRepository 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.Add(TableAccessLevelCacheKey, items);
        }
    }
}
