package uz.mobiuz.mobiservice.dev.utils

import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import uz.mobiuz.mobiservice.dev.model.SharedPref
import uz.mobiuz.mobiservice.dev.ui.global.CONSTANTS
import java.util.*

object LocaleHelper {
    fun setLocale(context: Context):Context {
        val lang = SharedPref(context).language
        return language(context,if (lang.isNotEmpty()) lang else CONSTANTS.RU )
    }

    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
    }
}