66 lines
1.9 KiB
C#
66 lines
1.9 KiB
C#
using System.Text.Json;
|
|
using Duempelkas.App.Services;
|
|
|
|
namespace Duempelkas.Infrastructure.Services;
|
|
|
|
public class SettingsService : ISettingsService
|
|
{
|
|
private readonly string SettingsPath;
|
|
|
|
public SettingsService(string? directory = null) => SettingsPath = Path.Combine(directory ?? Path.Combine(
|
|
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Duempelkas"), "settings.json");
|
|
|
|
private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
|
|
|
|
public async Task<string?> GetClubNameAsync()
|
|
{
|
|
var settings = await LoadAsync();
|
|
return settings.ClubName;
|
|
}
|
|
|
|
public async Task SetClubNameAsync(string? clubName)
|
|
{
|
|
var settings = await LoadAsync();
|
|
settings.ClubName = string.IsNullOrWhiteSpace(clubName) ? null : clubName.Trim();
|
|
await SaveAsync(settings);
|
|
}
|
|
|
|
public async Task<int> GetSetupStepAsync() => (await LoadAsync()).SetupStep;
|
|
public async Task SetSetupStepAsync(int step)
|
|
{
|
|
var settings = await LoadAsync();
|
|
settings.SetupStep = Math.Clamp(step, 0, 4);
|
|
await SaveAsync(settings);
|
|
}
|
|
|
|
private async Task<AppSettings> LoadAsync()
|
|
{
|
|
if (!File.Exists(SettingsPath))
|
|
return new AppSettings();
|
|
|
|
try
|
|
{
|
|
var json = await File.ReadAllTextAsync(SettingsPath);
|
|
return JsonSerializer.Deserialize<AppSettings>(json) ?? new AppSettings();
|
|
}
|
|
catch
|
|
{
|
|
return new AppSettings();
|
|
}
|
|
}
|
|
|
|
private async Task SaveAsync(AppSettings settings)
|
|
{
|
|
var dir = Path.GetDirectoryName(SettingsPath)!;
|
|
Directory.CreateDirectory(dir);
|
|
var json = JsonSerializer.Serialize(settings, JsonOptions);
|
|
await File.WriteAllTextAsync(SettingsPath, json);
|
|
}
|
|
|
|
private class AppSettings
|
|
{
|
|
public string? ClubName { get; set; }
|
|
public int SetupStep { get; set; }
|
|
}
|
|
}
|