package com.koko.drouter.base

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.SystemBarStyle
import androidx.activity.enableEdgeToEdge
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import com.didi.drouter.api.DRouter
import com.hjq.language.MultiLanguages
import com.koko.drouter.app.AppService
import com.koko.drouter.app.appService
import com.koko.drouter.event.EventService
import java.util.Locale
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.random.Random

abstract class BaseActivity<VB : ViewBinding>(
    bindingInflater: (LayoutInflater) -> VB
) : AppCompatActivity() {

    open val TAG = javaClass.simpleName
    private val tagNo = Random.nextInt(500)
    val binding by lazy(LazyThreadSafetyMode.NONE) {
        bindingInflater(layoutInflater)
    }

    lateinit var launcher: ActivityLauncher
    private var currentLocale: Locale = appService.getCurrentSpLocal()
    private var isLanguageRecreate: Boolean = false//判断当前activity有没有因为切换语言重新创建

    private val eventService by lazy {
        DRouter.build(EventService::class.java).getService()
    }

    private var onCreateI = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarColor()
        useDefaultImmersive()
        eventService.eventActivity(this)
        onCreateI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo onCreate ${javaClass.simpleName} $onCreateI")
        launcher = ActivityLauncher(this)
        setContentView(binding.root)
        eventActivity()
        changeLanguage()
        initView()
        initListener()
        initData()
    }

    private fun changeLanguage() {
        isLanguageRecreate = appService.changeActivityLanguage(this, currentLocale) {
            currentLocale = appService.getCurrentSpLocal()
        }
    }

    open fun initData() {}

    open fun setStatusBarColor(@ColorInt color: Int = Color.TRANSPARENT, isLight: Boolean = true) {
        enableEdgeToEdge(
            if (isLight) SystemBarStyle.light(color, color) else SystemBarStyle.dark(
                color
            )
        )
    }

    open fun useDefaultImmersive() {
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun eventActivity() {
        eventService.eventActivity(this)
    }


    protected open fun initView() {}

    protected open fun initListener() {}


    fun finishToMainTop() {
        val appService = DRouter.build(AppService::class.java).getService()
        appService.finishToMainTop(this)
    }

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

    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(MultiLanguages.attach(newBase))
    }


    /**
     * 避免在onResume--onPause周期内,多次调用
     * 在onStop中重置标志
     */
    private val onResumeCalled = AtomicBoolean(false)
    private var onResumeOneShootI = 0
    open fun onResumeOneShoot() {
        onResumeOneShootI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo onResumeOneShoot ${javaClass.simpleName} $onResumeOneShootI")
    }

    private var onResumeI = 0
    override fun onResume() {
        super.onResume()
        onResumeI++
//        LogEx.logDebug(TAG, "lifecycle $tagNo 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 $tagNo onStart ${javaClass.simpleName} $onStartI")
    }

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

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

}