using System;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Threading;

namespace MarcusLaw.OutlookAddin.UI.Services
{
    /// <summary>
    /// Strongly-typed wrapper around <see cref="ResourceManager"/>. The
    /// default culture is Hebrew (he-IL) — that's the user base. Switch by
    /// calling <see cref="SetCulture"/> from SettingsViewModel.
    /// </summary>
    public sealed class LocalizationManager
    {
        private const string BaseName = "MarcusLaw.OutlookAddin.UI.Resources.Strings";

        public static LocalizationManager Instance { get; } = new LocalizationManager();

        public ResourceManager ResourceManager { get; }

        private LocalizationManager()
        {
            ResourceManager = new ResourceManager(BaseName, typeof(LocalizationManager).Assembly);
        }

        public string Get(string key)
        {
            try
            {
                return ResourceManager.GetString(key, CultureInfo.CurrentUICulture) ?? key;
            }
            catch
            {
                return key;
            }
        }

        public string Format(string key, params object[] args)
        {
            var template = Get(key);
            try { return string.Format(CultureInfo.CurrentUICulture, template, args); }
            catch { return template; }
        }

        public static void SetCulture(string cultureName)
        {
            if (string.IsNullOrWhiteSpace(cultureName)) return;
            try
            {
                var ci = CultureInfo.GetCultureInfo(cultureName);
                Thread.CurrentThread.CurrentUICulture = ci;
                CultureInfo.DefaultThreadCurrentUICulture = ci;
            }
            catch (CultureNotFoundException) { /* leave as-is */ }
        }
    }
}
