package com.base.locationsharewhite.helper

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.base.locationsharewhite.R
import com.base.locationsharewhite.bean.ConstObject.appLanguageCountrySp
import com.base.locationsharewhite.bean.ConstObject.appLanguageSp
import com.base.locationsharewhite.ui.main.MainActivity
import com.base.locationsharewhite.utils.ActivityLauncher
import com.base.locationsharewhite.utils.LogEx
import com.hjq.language.MultiLanguages
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean

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

    protected abstract val binding: T

    lateinit var launcher: ActivityLauncher
    private var currentLocale: Locale? = null

    var onCreateI = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onCreateI++
        LogEx.logDebug(TAG, "lifecycle onCreate ${javaClass.simpleName} $onCreateI")
        launcher = ActivityLauncher(this)
        setContentView(binding.root)
        EventUtils.event("page_${javaClass.simpleName}")
        currentLocale = Locale(appLanguageSp, appLanguageCountrySp)
        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 attachBaseContext(newBase: Context?) {
        super.attachBaseContext(MultiLanguages.attach(newBase))
    }


    fun changeLanguage(currentActivity: Activity) {
        val spLanguage = Locale(appLanguageSp, appLanguageCountrySp)
        val flag = currentLocale != spLanguage

        var restart = false
        if (flag) {
            restart = MultiLanguages.setAppLanguage(this, spLanguage)
            if (restart) {
                currentLocale = Locale(appLanguageSp, appLanguageCountrySp)
            }
        }
        LogEx.logDebug(
            TAG, "changeLanguage " +
                    "flag=$flag  restart=$restart currentLocale=$currentLocale spLanguage=$spLanguage"
        )
        if (flag || restart) {
            // 1.使用 recreate 来重启 Activity，效果差，有闪屏的缺陷
//             recreate();

            // 2.使用常规 startActivity 来重启 Activity，有从左向右的切换动画
            // 稍微比 recreate 的效果好一点，但是这种并不是最佳的效果
            // startActivity(new Intent(this, LanguageActivity.class));
            // finish();

            // 3.我们可以充分运用 Activity 跳转动画，在跳转的时候设置一个渐变的效果，相比前面的两种带来的体验是最佳的
            //需要设置启动模式，避免AndroidManifest.xml设置singleTop启动模式导致重复启动不生效
            //这种方式如果设置了singleTop或者singleTask的，再次回到该activity无法改变于语言，因为还在堆栈里没有重新创建
            needRecreate()
            if (false) {
                LogEx.logDebug(TAG, "changeLanguage recreate")
                recreate()
            } else {
                startActivity(Intent(this, currentActivity::class.java))
                overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out)
                finish()
            }

        }

    }

    /**
     * 判断是否需要重新创建对SingleTop启动模式的有效
     */
    fun needRecreate(): Boolean {
        return TAG.contains("MainActivity")
    }


    private val onResumeCalled = AtomicBoolean(false)
    private var onResumeOneShootI = 0
    open fun onResumeOneShoot() {
        onResumeOneShootI++
        LogEx.logDebug(TAG, "lifecycle onResumeOneShootI ${javaClass.simpleName} $onResumeOneShootI")
    }

    private var onResumeI = 0
    override fun onResume() {
        super.onResume()
        onResumeI++
        LogEx.logDebug(TAG, "lifecycle onResume ${javaClass.simpleName} $onResumeI")

        if (!onResumeCalled.get()) {
            onResumeCalled.set(true)
            onResumeOneShoot()
        }
    }

    private var onStartI = 0
    override fun onStart() {
        super.onStart()
        onStartI++
        LogEx.logDebug(TAG, "lifecycle onStart ${javaClass.simpleName} $onStartI")
    }

    private var onStopI = 0
    override fun onStop() {
        super.onStop()
        onStopI++
        LogEx.logDebug(TAG, "lifecycle onStop ${javaClass.simpleName} $onStopI")
        onResumeCalled.set(false)
    }

    private var onPauseI = 0
    override fun onPause() {
        super.onPause()
        onPauseI++
        LogEx.logDebug(TAG, "lifecycle onPause ${javaClass.simpleName} $onPauseI")
    }

}