package com.mobiuz.app.dev.utils

import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import com.mobiuz.app.dev.model.SharedPref
import java.util.*

object LocaleHelper {
    fun setLocale(context: Context):Context {
        return language(context, SharedPref(context).language)
    }

    private fun language(context: Context, language: String):Context{
        val locale = Locale(language)
        Locale.setDefault(locale)
        val resources = context.resources
        val configuration = resources.configuration
        configuration.locale = locale
        resources.updateConfiguration(configuration, resources.displayMetrics)
        configuration.setLayoutDirection(locale)
        return context
    }

    private fun setAppLocale(
            context: Context,
            locale: String
    ): Context {
        val res = context.resources
        val dm = res.displayMetrics
        val conf = res.configuration
        conf.setLocale(Locale(locale.toLowerCase(Locale.getDefault())))
        res.updateConfiguration(conf, dm)
        return context
    }

    @TargetApi(Build.VERSION_CODES.N)
    private fun updateResources(
            context: Context,
            language: String
    ): Context? {
        val res = context.resources
        val dm = res.displayMetrics
        val conf = res.configuration
        conf.setLocale(Locale(language.toLowerCase(Locale.getDefault())))
        res.updateConfiguration(conf, dm)
        return context
    }


    private fun updateResourcesLegacy(
            context: Context,
            language: String
    ): Context? {
        val locale = Locale(language)
        Locale.setDefault(locale)
        val resources = context.resources
        val configuration = resources.configuration
        configuration.locale = locale
        configuration.setLayoutDirection(locale)
        resources.updateConfiguration(configuration, resources.displayMetrics)
        return context
    }
}