package com.atmob.keyboard_android.component.item

import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.atmob.keyboard_android.R
import com.atmob.keyboard_android.ext.click
import com.atmob.keyboard_android.ext.setGone
import com.atmob.keyboard_android.ext.setVisible
import com.atmob.keyboard_android.model.AiKeyboardKeyModel
import com.atmob.keyboard_android.util.LottieAnimationUtil
import me.drakeet.multitype.ItemViewBinder

/**
 * AI键盘按键条目
 */
class AiKeyboardKeyViewBinder(
    private val onItemClick: (itemView: View, item: AiKeyboardKeyModel) -> Unit
) :
    ItemViewBinder<AiKeyboardKeyModel, AiKeyboardKeyViewBinder.InnerViewHolder>() {
    override fun onCreateViewHolder(
        inflater: LayoutInflater,
        parent: ViewGroup
    ): InnerViewHolder {
        return InnerViewHolder(inflater.inflate(R.layout.item_ai_keyboard_key, parent, false))
    }

    override fun onBindViewHolder(
        holder: InnerViewHolder,
        item: AiKeyboardKeyModel
    ) {
        // 加载中，显示Loading，隐藏文字
        if (item.isLoading) {
            holder.vLoveFlyLoadingLottieView.setVisible()
            holder.vKeyText.setGone()
            LottieAnimationUtil.playLottieAnimation(
                holder.vLoveFlyLoadingLottieView,
                "lottie/anim_keyboard_love_fly.json"
            )
        } else {
            // 隐藏Loading，显示文字
            holder.vLoveFlyLoadingLottieView.setGone()
            holder.vKeyText.setVisible()
            // 文字
            holder.vKeyText.apply {
                text = item.text
            }
            LottieAnimationUtil.stopLottieAnimation(holder.vLoveFlyLoadingLottieView)
        }
        // 设置文字超出1行后，启用跑马灯效果（必须代码设置，xml中设置会无效）
        holder.vKeyText.apply {
            ellipsize = TextUtils.TruncateAt.MARQUEE
            isSingleLine = true
            isSelected = true
            isFocusable = true
            isFocusableInTouchMode = true
        }
        holder.itemView.click {
            onItemClick.invoke(holder.itemView, item)
        }
    }

    inner class InnerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val vKeyText: TextView = itemView.findViewById(R.id.key_text)
        val vLoveFlyLoadingLottieView: LottieAnimationView =
            itemView.findViewById(R.id.love_fly_loading_lottie_view)
    }
}