using Microsoft.Extensions.Options; using RustTools.Contracts.Services; using RustTools.Helpers; using RustTools.Models; using Windows.Storage; namespace RustTools.Services; public class LocalSettingsService : ILocalSettingsService { private const string _defaultApplicationDataFolder = "RustTools/ApplicationData"; private const string _defaultLocalSettingsFile = "LocalSettings.json"; private readonly IFileService _fileService; private readonly LocalSettingsOptions _options; private readonly string _localApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); private readonly string _applicationDataFolder; private readonly string _localsettingsFile; private IDictionary _settings; private bool _isInitialized; public LocalSettingsService(IFileService fileService, IOptions options) { _fileService = fileService; _options = options.Value; _applicationDataFolder = Path.Combine(_localApplicationData, _options.ApplicationDataFolder ?? _defaultApplicationDataFolder); _localsettingsFile = _options.LocalSettingsFile ?? _defaultLocalSettingsFile; _settings = new Dictionary(); } private async Task InitializeAsync() { if (!_isInitialized) { _settings = await Task.Run(() => _fileService.Read>(_applicationDataFolder, _localsettingsFile)) ?? new Dictionary(); _isInitialized = true; } } public async Task ReadSettingAsync(string key) { if (RuntimeHelper.IsMSIX) { if (ApplicationData.Current.LocalSettings.Values.TryGetValue(key, out var obj)) { return await Json.ToObjectAsync((string)obj); } } else { await InitializeAsync(); if (_settings != null && _settings.TryGetValue(key, out var obj)) { return await Json.ToObjectAsync((string)obj); } } return default; } public async Task SaveSettingAsync(string key, T value) { if (RuntimeHelper.IsMSIX) { ApplicationData.Current.LocalSettings.Values[key] = await Json.StringifyAsync(value); } else { await InitializeAsync(); _settings[key] = await Json.StringifyAsync(value); await Task.Run(() => _fileService.Save(_applicationDataFolder, _localsettingsFile, _settings)); } } }