package tech.starwin.utils.context_utils;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.util.DisplayMetrics;


import java.util.HashMap;
import java.util.Locale;

import tech.starwin.LibConfig;
import tech.starwin.utils.LogUtils;

public class AppLanguageUtils {


    public static void setLanguage(Context context, String language) {
        Resources resources = context.getApplicationContext().getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();

        Locale locale = getLocale(language);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            config.setLocale(locale);
        } else {
            config.locale = locale;
        }
        resources.updateConfiguration(config, dm);
    }

    public static Locale getLocale(String language) {
        Locale locale = null;
        switch (language) {
            case "en":
                locale = Locale.ENGLISH;
                break;
            case "zh":
                locale = Locale.SIMPLIFIED_CHINESE;
                break;
            case "in":
                locale =  new Locale("in");
                break;
            default:
                locale = Locale.getDefault();
                break;
        }
        return locale;
    }


    public static Context attachBaseContext(Context context, String language) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, getLocale(language));
        } else {
            return context;
        }
    }


    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, Locale locale) {
        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        configuration.setLocales(new LocaleList(locale));
        return context.createConfigurationContext(configuration);
    }

}