package com.atmob.keyboard_android.component.item

import android.graphics.Typeface
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.atmob.keyboard_android.R
import com.atmob.keyboard_android.enums.KeyboardType
import com.atmob.keyboard_android.ext.click
import com.atmob.keyboard_android.ext.loadUrlImageToCorner
import com.atmob.keyboard_android.util.bridge.model.resp.KeyboardInfo
import me.drakeet.multitype.ItemViewBinder

/**
 * 键盘选择条目
 */
class KeyboardSelectViewBinder(
    private val onItemClick: (item: KeyboardInfo) -> Unit
) :
    ItemViewBinder<KeyboardInfo, KeyboardSelectViewBinder.InnerViewHolder>() {
    override fun onCreateViewHolder(
        inflater: LayoutInflater,
        parent: ViewGroup
    ): InnerViewHolder {
        return InnerViewHolder(inflater.inflate(R.layout.item_keyboard_select, parent, false))
    }

    override fun onBindViewHolder(
        holder: InnerViewHolder,
        item: KeyboardInfo
    ) {
        val context = holder.itemView.context

        val isSystemKeyboard = KeyboardType.isSystem(item.type ?: "")
        val iconDefaultResId = if (isSystemKeyboard) {
            R.mipmap.ic_common_keyboard_icon
        } else {
            R.mipmap.ic_keyboard_default_icon
        }

        holder.vIcon.loadUrlImageToCorner(item.imageUrl, 24f, iconDefaultResId)
        holder.vName.text = item.name

        // 选中
        if (item.isSelect == true) {
            holder.itemContainer.setBackgroundResource(R.drawable.bg_keyboard_selected)
            holder.vName.apply {
                setTextColor(context.resources.getColor(R.color.text_color_white))
                setTypeface(typeface, Typeface.BOLD)
            }
        } else {
            // 未选中
            holder.itemContainer.setBackgroundResource(R.drawable.bg_keyboard_normal)
            holder.vName.apply {
                setTextColor(context.resources.getColor(R.color.text_color_primary))
                setTypeface(typeface, Typeface.NORMAL)
            }
        }

        holder.itemView.click {
            onItemClick.invoke(item)
        }
    }

    inner class InnerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val itemContainer: ViewGroup = itemView.findViewById(R.id.item_container)
        val vIcon: ImageView = itemView.findViewById(R.id.icon)
        val vName: TextView = itemView.findViewById(R.id.name)
    }
}