using Billing.iOS;
using Foundation;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Threading;

namespace Billing.Languages
{
    public partial class PlatformCulture
    {
        public partial string GetNamespace()
        {
            return typeof(AppDelegate).Namespace;
        }

        public partial void Init()
        {
            string lang;
            if (NSLocale.PreferredLanguages.Length > 0)
            {
                var pref = NSLocale.PreferredLanguages[0];
                lang = iOSToDotnetLanguage(pref);
            }
            else
            {
                lang = "zh-CN";
            }

            CultureInfo ci;
            Init(lang);
            try
            {
                ci = new CultureInfo(Language);
            }
            catch (CultureNotFoundException e)
            {
                try
                {
                    var fallback = ToDotnetFallbackLanguage();
                    Helper.Debug($"{lang} failed, trying {fallback} ({e.Message})");
                    ci = new CultureInfo(fallback);
                }
                catch (CultureNotFoundException e1)
                {
                    Helper.Error("culture.get", $"{lang} couldn't be set, using 'zh-CN' ({e1.Message})");
                    ci = new CultureInfo("zh-CN");
                }
            }

            Thread.CurrentThread.CurrentCulture = ci;
            Thread.CurrentThread.CurrentUICulture = ci;

            Helper.Debug($"CurrentCulture set: {ci.Name}");
        }

        [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
        private static string iOSToDotnetLanguage(string iOSLanguage)
        {
            //certain languages need to be converted to CultureInfo equivalent
            string netLanguage = iOSLanguage switch
            {
                // Not supported .NET culture
                "ms-MY" or "ms-SG" => "ms", // closest supported
                                            // "Schwiizertüütsch (Swiss German)" not supported .NET culture
                "gsw-CH" => "de-CH", // closest supported

                // add more application-specific cases here (if required)
                // ONLY use cultures that have been tested and known to work

                _ => iOSLanguage,
            };
            Helper.Debug($"iOS Language: {iOSLanguage}, .NET Language/Locale: {netLanguage}");
            return netLanguage;
        }
    }
}