package com.develop.setting.init.ui


import android.annotation.SuppressLint
import android.app.backup.BackupManager
import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LanguageUtils
import com.develop.food.base.common.CURRENT_LANGUAGE
import com.develop.food.base.common.LANGUAGE_FROM_SETTING
import com.develop.food.base.common.LANGUAGE_SETTING
import com.develop.food.base.data.DataFactory
import com.develop.food.base.event.FinishAtyEvent
import com.develop.food.base.router.Screens
import com.develop.food.base.router.navigateTo
import com.develop.food.base.ui.BaseActivity
import com.develop.food.base.utils.MmkvUtils
import com.develop.food.base.utils.ResDimension
import com.develop.food.base.utils.SerialportLibUtils
import com.develop.food.base.utils.TuyaUtils.context
import com.develop.food.base.utils.isNightTheme
import com.develop.food.base.widgets.CancelConfirmDialog
import com.develop.setting.R
import com.develop.setting.databinding.ActivityLanguageBinding
import com.develop.setting.init.adapter.LanguageAdapterV2
import com.develop.setting.init.adapter.LanguageAdapterV3
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import org.greenrobot.eventbus.Subscribe
import java.lang.reflect.Method
import java.util.Locale


@Route(path = Screens.Setting.LANGUAGE)
class LanguageActivity : BaseActivity<ActivityLanguageBinding>() {
    private var languageAdapter = LanguageAdapterV2()
    private var languageAdapter1 = LanguageAdapterV3()
    private var selectPosition = -1
    private var locales = arrayOf<Locale>()
    private var isFromSetting = false


    override fun createViewBinding(inflater: LayoutInflater): ActivityLanguageBinding {
        return ActivityLanguageBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isFromSetting = intent.extras?.getBoolean(LANGUAGE_FROM_SETTING) ?: false


        if (isFromSetting) {
            binding.ivBanner.visibility = View.GONE
            binding.topBar.visibility = View.VISIBLE
            binding.tvLanguage.visibility = View.GONE
            binding.topBar.setTopBarTitle(getString(R.string.Language))
            val params = binding.languageRecycle.layoutParams as RelativeLayout.LayoutParams
            params.topMargin = ResDimension(R.dimen.convert_251px).toInt()
            binding.languageRecycle.layoutParams = params
            binding.topBar.listenBackClick {
                finish()
            }
        }
        if (isNightTheme()) {
            languageAdapter1.setList(DataFactory.createLanguageDataV2(resources))
            binding.languageRecycle.apply {
                adapter = languageAdapter1
                selectPosition = getSelectedPos()
            }

            languageAdapter1.setOnItemClickListener { adapter, view, position ->
                languageAdapter1.updateSelectedPosition(position)
                this.selectPosition = position
//            updateLanguage()
            }

        } else {
            languageAdapter.setList(DataFactory.createLanguageDataV2(resources))
            binding.languageRecycle.apply {
                adapter = languageAdapter
                selectPosition = getSelectedPos()
            }

            languageAdapter.setOnItemClickListener { adapter, view, position ->
                languageAdapter.updateSelectedPosition(position)
                this.selectPosition = position
//            updateLanguage()
            }

        }


        if (isFromSetting) {
            binding.tvNext.setText(getString(R.string.confirm))
        }

        binding.tvNext.setOnClickListener {
            if (CofarSDK.devInfo().status == DevStatus.RUNNING.toInt()) {
                var dailog = CancelConfirmDialog()
                dailog.title = getString(R.string.change_lang_tips)
                dailog.showCancel = false;

                dailog.onDialogClickListener = object : CancelConfirmDialog.OnDialogClickListener {
                    override fun onConfirm() {

                    }

                    override fun onCancel() {
                    }

                }
                dailog.showDialog(supportFragmentManager, "confirm")
                return@setOnClickListener
            }

            if (isFromSetting) {

                if (isNightTheme()) {
                    if (languageAdapter1.data[selectPosition].value == MmkvUtils.getString(
                            CURRENT_LANGUAGE
                        )
                    ) {
                        finish()
                        return@setOnClickListener
                    }
                } else {
                    if (languageAdapter.data[selectPosition].value == MmkvUtils.getString(
                            CURRENT_LANGUAGE
                        )
                    ) {
                        finish()
                        return@setOnClickListener
                    }
                }
                var dailog = CancelConfirmDialog()
                dailog.title = getString(R.string.change_lang_tips2)

                dailog.onDialogClickListener = object : CancelConfirmDialog.OnDialogClickListener {
                    override fun onConfirm() {

                        updateLanguage()
//                        finish()
//                        navigateTo(Screens.Main.ENTRANCE_CHOSEN)


                        val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
                        pm.reboot("")

//                        val manager  = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
//                        manager.restartPackage("com.develop.foodcooking")


                    }

                    override fun onCancel() {
                    }

                }

                dailog.showDialog(supportFragmentManager, "tips2")


            } else {
                updateLanguage()
                navigateTo(Screens.Setting.POLICY)
            }


        }
    }

    private fun updateLanguage() {
        var index = 0
        index = selectPosition
        if (selectPosition == -1) {
            index = 0
        }
        //添加状态，避免设置语言反复设置
        MmkvUtils.save(LANGUAGE_SETTING,true)
        if (isNightTheme()) {
            languageAdapter1.data[selectPosition].apply {
//                updateLanguage(Locale(this.value.lowercase(), this.value.uppercase()))
                MmkvUtils.save(CURRENT_LANGUAGE, this.value)
//                setLanguage(this.value.lowercase())
                LanguageUtils.applyLanguage(Locale(this.value.lowercase(), this.value.uppercase()))
            }
        } else {
            languageAdapter.data[selectPosition].apply {
//                updateLanguage(Locale(this.value.lowercase(), this.value.uppercase()))
                MmkvUtils.save(CURRENT_LANGUAGE, this.value)
//                setLanguage(this.value.lowercase())
                LanguageUtils.applyLanguage(Locale(this.value.lowercase(), this.value.uppercase()))
            }
        }
    }


    private  fun  setLanguage(language:String){
        val resources = applicationContext.resources
        val dm = resources.displayMetrics
        val config = resources.configuration
        val newLocale = SerialportLibUtils.getLocale(language)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            config.setLocale(newLocale) // newLocale是你想要切换到的语言环境
            applicationContext.createConfigurationContext(config)
        } else {
            config.locale = newLocale
        }
        resources.updateConfiguration(config, dm)
    }
    private fun getSelectedPos(): Int {


        if (isNightTheme()) {
            for ((index, item) in languageAdapter1.data.withIndex()) {
                if (MmkvUtils.getString(CURRENT_LANGUAGE) == item.value) {
                    languageAdapter1.updateSelectedPosition(index)
                    return index
                }
            }
        } else {
            for ((index, item) in languageAdapter.data.withIndex()) {
                if (MmkvUtils.getString(CURRENT_LANGUAGE) == item.value) {
                    languageAdapter.updateSelectedPosition(index)
                    return index
                }
            }
        }


        return 0


    }

    @Subscribe
    fun onFinishAtyEvent(event: FinishAtyEvent) {
        finish()
    }

    @SuppressLint("PrivateApi", "DiscouragedPrivateApi")
    fun updateLanguage(locale: Locale) {
        try {
            val objIActMag: Any
            val clzIActMag = Class.forName("android.app.IActivityManager")
            val clzActMagNative = Class
                .forName("android.app.ActivityManagerNative")
            //amn = ActivityManagerNative.getDefault();
            val `mtdActMagNative$getDefault`: Method = clzActMagNative
                .getDeclaredMethod("getDefault")
            objIActMag = `mtdActMagNative$getDefault`.invoke(clzActMagNative)!!
            // objIActMag = amn.getConfiguration();
            val `mtdIActMag$getConfiguration`: Method = clzIActMag
                .getDeclaredMethod("getConfiguration")
            val config: Configuration = `mtdIActMag$getConfiguration`
                .invoke(objIActMag) as Configuration
            // set the locale to the new value
            config.locale = locale
            //持久化  config.userSetLocale = true;
            val clzConfig = Class
                .forName("android.content.res.Configuration")
            val userSetLocale = clzConfig
                .getField("userSetLocale")
            userSetLocale[config] = true
            // 此处需要声明权限:android.permission.CHANGE_CONFIGURATION
            // 会重新调用 onCreate();
            val clzParams = arrayOf<Class<*>>(
                Configuration::class.java
            )
            // objIActMag.updateConfiguration(config);
            val `mtdIActMag$updateConfiguration`: Method = clzIActMag
                .getDeclaredMethod("updateConfiguration", *clzParams)
            `mtdIActMag$updateConfiguration`.invoke(objIActMag, config)
            BackupManager.dataChanged("com.android.providers.settings")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}