package tech.starwin.utils.context_utils;

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

import com.common.toolbox.app_utils.DeviceInfo;

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

import tech.starwin.utils.LogUtils;

public class AppLanguageUtils {


    public static void setLanguage(Context context, String language) {

        if (DeviceInfo.DEFAULT_LANGUAGE == "") {
            DeviceInfo.DEFAULT_LANGUAGE = "country=" + Locale.getDefault().getCountry() + "&" +
                    "language=" + Locale.getDefault().getLanguage() + "&" +
                    "display_country=" + Locale.getDefault().getDisplayCountry() + "&" +
                    "display_language=" + Locale.getDefault().getDisplayLanguage() + "&" +
                    "display_name=" + Locale.getDefault().getDisplayName();

        }

        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 = Locale.ROOT;
                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);
    }

}