package com.atmob.keyboard_android.component.base

import android.content.Context
import android.util.AttributeSet
import com.atmob.keyboard_android.ext.getAllChildView
import com.atmob.keyboard_android.util.ViewTreeHelper

/**
 * 可以包含其他子组件的容器组件
 */
abstract class GroupComponent @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AnimationComponent(context, attrs, defStyleAttr) {
    /**
     * 直接子组件列表，也就是父组件下的直接子组件，不能隔代
     */
    private val mDirectChildComponentList: MutableList<IUIComponent> = mutableListOf()

    override fun onFinishInflate() {
        super.onFinishInflate()
        // 获取所有直接子组件
        val childComponentList = getAllChildView().filter { view ->
            view is IUIComponent
        }.map {
            it as IUIComponent
        }.toList()
        mDirectChildComponentList.clear()
        mDirectChildComponentList.addAll(childComponentList)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        mDirectChildComponentList.clear()
    }

    /**
     * 获取所有直接子组件
     */
    fun getDirectChildComponentList(): MutableList<IUIComponent> {
        return mDirectChildComponentList
    }

    /**
     * 通过组件Class类型，查找子组件
     */
    fun <T : IUIComponent> getChildComponent(componentClass: Class<T>): T? {
        return ViewTreeHelper.findTargetView(this, componentClass)
    }
}