package me.echeung.moemoekyun.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.util.Log;

import java.util.Locale;

import me.echeung.moemoekyun.App;

// https://proandroiddev.com/change-language-programmatically-at-runtime-on-android-5e6bc15c758
public class LocaleUtil {

    protected static final String DEFAULT = "default";

    public static Context setLocale(@NonNull Context context) {
        if (App.getPreferenceUtil() == null) {
            return context;
        }

        final String language = App.getPreferenceUtil().getLanguage();
        return setLocale(context, language);
    }

    public static Context setLocale(@NonNull Context context, String language) {
        final Resources res = context.getResources();
        final Configuration config = new Configuration(res.getConfiguration());

        if (!language.equals(DEFAULT)) {
            final Locale locale = new Locale(language);
            Locale.setDefault(locale);
            config.setLocale(locale);
        }

        context = context.createConfigurationContext(config);
        return context;
    }

    public static void setTitle(@NonNull Activity activity) {
        try {
            int label = activity
                    .getPackageManager()
                    .getActivityInfo(activity.getComponentName(), PackageManager.GET_META_DATA)
                    .labelRes;
            if (label != 0) {
                activity.setTitle(label);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(activity.getLocalClassName(), e.getMessage(), e);
        }
    }

}

@@ -1069,20 +1069,238 @@
     
-final 
 Locale
+ locale;%0A            if (language.contains(%22-r%22)) %7B%0A                String%5B%5D languageParts = language.split(%22-r%22);%0A                locale = new Locale(languageParts%5B0%5D, languageParts%5B1%5D);%0A            %7D else %7B%0A               
  loc
@@ -1323,24 +1323,38 @@
 (language);%0A
+            %7D%0A
             

Fix setting for regionalized locales