package com.atmob.keyboard_android.component.base

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import com.atmob.keyboard_android.component.base.animator.ComponentAnimator
import com.atmob.keyboard_android.component.base.animator.impl.NoAnimationAnimator
import com.atmob.keyboard_android.component.widget.CustomOrderFrameLayout

/**
 * 带有动画功能的组件基类
 */
abstract class AnimationComponent @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : CustomOrderFrameLayout(context, attrs, defStyleAttr), IUIComponent {
    /**
     * 动画执行器
     */
    private val mComponentAnimator: ComponentAnimator

    /**
     * 组件是否正在显示
     */
    private var isComponentShowing: Boolean = false

    init {
        // 创建组件动画执行器
        mComponentAnimator = getComponentAnimator()
        mComponentAnimator.attachUIComponent(this)
    }

    override fun show(onStart: (() -> Unit)?, onFinish: (() -> Unit)?) {
        mComponentAnimator.show(onStart, onFinish = {
            isComponentShowing = true
            onComponentShow()
            onFinish?.invoke()
        })
    }

    override fun hide(onStart: (() -> Unit)?, onFinish: (() -> Unit)?) {
        mComponentAnimator.hide(onStart, onFinish = {
            isComponentShowing = false
            onComponentHide()
            onFinish?.invoke()
        })
    }

    override fun asView(): ViewGroup {
        return this
    }

    /**
     * 获取组件的动画执行器
     */
    protected open fun getComponentAnimator(): ComponentAnimator {
        // 默认不使用动画，进行切换
        return NoAnimationAnimator()
    }

    /**
     * 组件打开时回调
     */
    protected open fun onComponentShow() {
    }

    /**
     * 组件关闭时回调
     */
    protected open fun onComponentHide() {
    }

    /**
     * 组件是否正在展示
     */
    fun isComponentShowing(): Boolean {
        return isComponentShowing
    }
}