using Billing.Droid;
using System.Globalization;
using System.Threading;

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

        public partial void Init()
        {
            var locale = Java.Util.Locale.Default;
            string lang = AndroidToDotnetLanguage($"{locale.Language}-{locale.Country}");

            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}");
        }

        private static string AndroidToDotnetLanguage(string androidLanguage)
        {
            //certain languages need to be converted to CultureInfo equivalent
            string netLanguage = androidLanguage switch
            {
                // Not supported .NET culture
                "ms-BN" or "ms-MY" or "ms-SG" => "ms", // closest supported
                                                       // "Indonesian (Indonesia)" has different code in .NET
                "in-ID" => "id-ID",  // correct code for .NET
                                     // "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

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