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

namespace Hotline.Caching.Services
{
    public class SysDicDataCacheManager : ISystemDicDataCacheManager, IScopeDependency
    {
        private readonly IRepository<SystemDicData> _sysDicDataRepository;
        private readonly ITypedCache<IReadOnlyList<SystemDicData>> _cacheSysDicData;

        public SysDicDataCacheManager(IRepository<SystemDicData> sysDicDataRepository, ITypedCache<IReadOnlyList<SystemDicData>> cacheSysDicData)
        {
            _sysDicDataRepository = sysDicDataRepository;
            _cacheSysDicData = cacheSysDicData;
        }

        public IReadOnlyList<SystemDicData> GetSysDicDataCache(string code)
        {
            var sysDicDataList = _cacheSysDicData.GetOrSet(code, k =>
            {
                return _sysDicDataRepository.Queryable().Where(x => x.DicTypeCode == code).OrderBy(x=>x.Sort).ToTreeAsync(x => x.Children, it => it.ParentId, "").GetAwaiter().GetResult();
            });
            return sysDicDataList;
        }

        public void RemoveSysDicDataCache(string code)
        {
            _cacheSysDicData.Remove(code);
        }
    }
}
