package com.base.locationsharewhite.helper

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.base.locationsharewhite.bean.ConstObject.appLanguageSp
import com.base.locationsharewhite.bean.ConstObject.changeLanguageSp
import com.base.locationsharewhite.ui.main.MainActivity
import com.base.locationsharewhite.utils.ActivityLauncher
import com.base.locationsharewhite.utils.LanguageUtils.changeAppLanguage
import com.base.locationsharewhite.utils.LogEx

abstract class BaseActivity<T : ViewBinding> : AppCompatActivity() {
    private val TAG = "BaseActivity"

    protected abstract val binding: T

    lateinit var launcher: ActivityLauncher


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        launcher = ActivityLauncher(this)
        setContentView(binding.root)

//        EventUtils.event("page_${javaClass.simpleName}")
        initView()
        initListener()
    }

    protected abstract fun initView()

    protected open fun initListener() {}


    fun finishToMain() {
        if (this !is MainActivity && !ActivityManagerUtils.getInstance().isActivityInStack(MainActivity::class.java)) {
            startActivity(Intent(this, MainActivity::class.java))
        }
        finish()
    }

    var dialog: Dialog? = null
    override fun onDestroy() {
        super.onDestroy()
        ActivityManagerUtils.getInstance().removeActivity(this)
        if (dialog != null) {
            dialog?.dismiss()
            dialog = null
        }
    }


    override fun onResume() {
        super.onResume()
    }

    fun updateAppLanguage(
        activityLanguage: String,
        activityTag: String? = null,
        activityChangeCallback: ((language: String) -> Unit)? = null
    ): Boolean {
        LogEx.logDebug(
            TAG,
            "activityTag=$activityTag " +
                    "appLanguageSp=$appLanguageSp " +
                    "changeLanguageSp=$changeLanguageSp " +
                    "activityLanguage=$activityLanguage"
        )
        var isRecreate = false

        if (appLanguageSp != changeLanguageSp || activityLanguage != changeLanguageSp) {

            changeAppLanguage(this, changeLanguageSp)
            // Restart the app
            appLanguageSp = changeLanguageSp
            activityChangeCallback?.invoke(changeLanguageSp)
            LogEx.logDebug(TAG, "activityTag=$activityTag recreate")
            isRecreate = true

            //https://stackoverflow.com/questions/63209993/getting-lifecycle-exception-while-recreating-the-activity
            //MIUI recreate
            this@BaseActivity.recreate()
        }
        return isRecreate
    }

    fun isLanguageRecreate(activityLanguage: String): Boolean {
        return appLanguageSp != changeLanguageSp || activityLanguage != changeLanguageSp
    }

}