package com.atmob.keyboard_android.component

import com.atmob.keyboard_android.component.base.IUIComponent

/**
 * 组件协调者，也是组件中介，负责组件之间的通信和交互
 */
object ComponentMediator {
    /**
     * 组件Map，保存组件的实例
     */
    private val mComponentMap: MutableMap<String, IUIComponent> = mutableMapOf()

    private var mOnComponentUpdateListener: OnComponentUpdateListener? = null

    interface OnComponentUpdateListener {
        /**
         * 组件注册时回调
         */
        fun onComponentRegister(componentName: String, component: IUIComponent)

        /**
         * 组件解注册时回调
         */
        fun onComponentUnRegister(componentName: String, component: IUIComponent)
    }

    /**
     * 设置监听器
     */
    fun setOnComponentUpdateListener(listener: OnComponentUpdateListener) {
        this.mOnComponentUpdateListener = listener
    }

    /**
     * 注册组件
     *
     * @param componentInterfaceClazz 组件的接口Class类
     * @param component 组件实例
     */
    fun <T : IUIComponent> registerComponent(
        componentInterfaceClazz: Class<T>,
        component: IUIComponent
    ) {
        registerComponent(componentInterfaceClazz.name, component)
    }

    /**
     * 注册组件
     *
     * @param componentName 组件名称
     * @param component 组件实例
     */
    fun registerComponent(
        componentName: String,
        component: IUIComponent
    ) {
        // 如果已经注册过了，不能重复注册
        if (mComponentMap.contains(componentName)) {
            throw RuntimeException("组件不能重复注册，请保证组件名称唯一性")
        }
        mComponentMap[componentName] = component
        mOnComponentUpdateListener?.onComponentRegister(componentName, component)
    }

    /**
     * 取消注册组件
     *
     * @param componentInterfaceClazz 组件的接口Class类
     */
    fun <T : IUIComponent> unRegisterComponent(componentInterfaceClazz: Class<T>) {
        unRegisterComponent(componentInterfaceClazz.name)
    }

    /**
     * 取消注册组件
     *
     * @param componentName 组件名称
     */
    fun unRegisterComponent(componentName: String) {
        val component = mComponentMap.remove(componentName)
        if (component != null) {
            mOnComponentUpdateListener?.onComponentUnRegister(componentName, component)
        }
    }

    /**
     * 查找组件
     *
     * @param componentInterfaceClazz 组件的接口Class类
     */
    fun <T : IUIComponent> findComponent(componentInterfaceClazz: Class<T>): T? {
        return mComponentMap[componentInterfaceClazz.name] as T?
    }

    /**
     * 查找组件
     *
     * @param componentName 组件名称
     */
    fun <T : IUIComponent> findComponent(componentName: String): T? {
        return mComponentMap[componentName] as T?
    }
}