package com.atmob.keyboard_android.component.base

import android.content.Context
import android.content.res.TypedArray
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import com.atmob.keyboard_android.R
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 {
    /**
     * 组件名称，不设置则为null
     */
    private var mComponentName: String? = null

    init {
        // 初始化自定义属性
        initAttr(context, attrs)
        // 组件创建，注册组件，如果有自定义组件名称，则使用自定义的，否则使用接口的类名来注册组件
        doRegisterComponent()
        val view = LayoutInflater.from(context).inflate(onInflateViewId(), this, true)
        findView(view)
        bindView(view)
    }

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

    /**
     * 注册组件
     */
    private fun doRegisterComponent() {
        val componentName = mComponentName ?: ""
        if (componentName.isNotBlank()) {
            ComponentMediator.registerComponent(componentName, this)
        } else {
            ComponentMediator.registerComponent(getComponentInterfaceClazz(), this)
        }
    }

    /**
     * 解注册组件
     */
    private fun doUnRegisterComponent() {
        val componentName = mComponentName ?: ""
        if (componentName.isNotBlank()) {
            ComponentMediator.unRegisterComponent(componentName)
        } else {
            ComponentMediator.unRegisterComponent(getComponentInterfaceClazz())
        }
    }

    /**
     * 初始化自定义属性
     */
    private fun initAttr(context: Context, attrs: AttributeSet? = null) {
        var typeArray: TypedArray? = null
        try {
            typeArray =
                context.obtainStyledAttributes(attrs, R.styleable.BaseUIComponent)
            mComponentName = typeArray.getString(R.styleable.BaseUIComponent_uic_component_name)
        } finally {
            typeArray?.recycle()
        }
    }

    /**
     * 获取组件的视图布局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>
}