using System.ComponentModel;
using System.Globalization;
using System.Resources;

namespace SharepointToolbox.Localization;

/// <summary>
/// Singleton INotifyPropertyChanged string lookup enabling runtime culture switching without restart.
/// WPF bindings use: Source={x:Static loc:TranslationSource.Instance}, Path=[key]
/// On CurrentCulture change, fires PropertyChanged with empty string to signal all properties changed,
/// which causes WPF to re-evaluate all bindings to this source.
/// </summary>
public class TranslationSource : INotifyPropertyChanged
{
    public static readonly TranslationSource Instance = new();

    private ResourceManager _resourceManager = Strings.ResourceManager;
    private CultureInfo _currentCulture = CultureInfo.CurrentUICulture;

    private TranslationSource() { }

    public string this[string key] =>
        _resourceManager.GetString(key, _currentCulture) ?? $"[{key}]";

    public CultureInfo CurrentCulture
    {
        get => _currentCulture;
        set
        {
            if (Equals(_currentCulture, value)) return;
            _currentCulture = value;
            Thread.CurrentThread.CurrentUICulture = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty));
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;
}
