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

namespace Hotline.Caching.Services
{
    public class SystemSettingCacheManager : ISystemSettingCacheManager, IScopeDependency
    {

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

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

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

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