package com.atmob.keyboard_android.component.base

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import com.atmob.keyboard_android.component.ComponentMediator

/**
 * UI组件抽象类，定义生命周期方法
 */
abstract class BaseUIComponent<T : IUIComponent> @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : GroupComponent(context, attrs, defStyleAttr), IBusinessComponent {
    init {
        // 组件创建，注册组件
        ComponentMediator.registerComponent(getComponentInterfaceClazz(), this)
        val view = LayoutInflater.from(context).inflate(onInflateViewId(), this, true)
        findView(view)
        bindView(view)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        // 组件销毁，解开注册
        ComponentMediator.unRegisterComponent(getComponentInterfaceClazz())
    }

    /**
     * 获取组件的视图布局Id
     */
    abstract fun onInflateViewId(): Int

    /**
     * 查找控件
     */
    abstract fun findView(view: View)

    /**
     * 绑定控件
     */
    abstract fun bindView(view: View)

    override fun isNeedLogin(): Boolean {
        // 默认都不需要登录，就能打开
        return false
    }

    /**
     * 返回组件的接口
     */
    abstract fun getComponentInterfaceClazz(): Class<T>
}