using Hotline.Caches;
using Hotline.Settings;
using XF.Domain.Cache;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;

namespace Hotline.CacheManager
{
    public class SystemSettingCacheManager:ISystemSettingCacheManager,IScopeDependency
    {

        private readonly ITypedCache<SystemSetting> _cacheSystemSetting;
        private readonly ISystemSettingRepository _systemSettingRepository;

        public SystemSettingCacheManager(ITypedCache<SystemSetting> cacheSystemSetting, ISystemSettingRepository systemSettingRepository)
        {
            _cacheSystemSetting = cacheSystemSetting;
            _systemSettingRepository = systemSettingRepository;
        }

        public SystemSetting GetSetting(string code)
        {
            var setting = _cacheSystemSetting.GetOrAdd(code, x =>
            {
                var dbsetting = _systemSettingRepository.GetAsync(d => d.Code == code).GetAwaiter().GetResult();
                if (dbsetting==null)
                    throw new UserFriendlyException("无效系统设置");
                return dbsetting;
            });
            return setting;
        }

        public bool DelSystemSetting(string code)
        {
            return _cacheSystemSetting.Remove(code);
        }
    }
}
