package com.atmob.keyboard_android.component.widget.lifecycle

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner

/**
 * 普通的ViewGroup，不支持Jetpack的Lifecycle组件和ViewModel组件，该类进行自定义支持
 */
open class LifecycleViewGroup @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), LifecycleOwner, ViewModelStoreOwner {
    // 实现ViewModelStore组件
    override val viewModelStore by lazy {
        ViewModelStore()
    }

    // 实现Lifecycle组件
    private val lifecycleRegistry = LifecycleRegistry(this).apply {
        currentState = Lifecycle.State.INITIALIZED
        currentState = Lifecycle.State.CREATED
    }

    override val lifecycle: Lifecycle
        get() = lifecycleRegistry

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        // View添加到View树中，变更状态为可见
        lifecycleRegistry.currentState = Lifecycle.State.STARTED
        updateStateOnVisibility()
    }

    override fun onDetachedFromWindow() {
        // View从View树中移除，变更状态为销毁
        lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
        // 清理ViewModel
        viewModelStore.clear()
        super.onDetachedFromWindow()
    }

    override fun onVisibilityChanged(changedView: View, visibility: Int) {
        super.onVisibilityChanged(changedView, visibility)
        // 监听可见性变化，变更状态
        if (changedView == this) {
            updateStateOnVisibility()
        }
    }

    /**
     * 可见性变化，变更状态
     */
    private fun updateStateOnVisibility() {
        when (visibility) {
            VISIBLE -> {
                if (lifecycleRegistry.currentState == Lifecycle.State.STARTED) {
                    lifecycleRegistry.currentState = Lifecycle.State.RESUMED
                }
            }

            INVISIBLE, GONE -> {
                if (lifecycleRegistry.currentState == Lifecycle.State.RESUMED) {
                    lifecycleRegistry.currentState = Lifecycle.State.STARTED
                }
            }
        }
    }

    /**
     * 获取LifecycleOwner
     */
    fun getLifecycleOwner(): LifecycleOwner {
        return this
    }
}