using WorkTracker.Domain;

namespace WorkTracker.Services.Settings;

public sealed class AppThemeState
{
    private readonly IAppSettingsService appSettingsService;
    private AppThemeMode? currentThemeMode;

    public AppThemeState(IAppSettingsService appSettingsService)
    {
        this.appSettingsService = appSettingsService;
    }

    public event Action<AppThemeMode>? ThemeModeChanged;

    public AppThemeMode CurrentThemeMode => currentThemeMode ?? AppThemeMode.System;

    public async Task<AppThemeMode> EnsureLoadedAsync(CancellationToken cancellationToken = default)
    {
        if (currentThemeMode.HasValue)
        {
            return currentThemeMode.Value;
        }

        var settings = await appSettingsService.GetAsync(cancellationToken);
        currentThemeMode = settings.ThemeMode;
        return CurrentThemeMode;
    }

    public void SetThemeMode(AppThemeMode themeMode)
    {
        if (currentThemeMode == themeMode)
        {
            return;
        }

        currentThemeMode = themeMode;
        ThemeModeChanged?.Invoke(themeMode);
    }
}