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.loadUrlImage
import com.atmob.keyboard_android.model.KeyboardSelectModel
import me.drakeet.multitype.ItemViewBinder

/**
 * 键盘选择条目
 */
class KeyboardSelectViewBinder(
    private val onItemClick: (item: KeyboardSelectModel) -> Unit
) :
    ItemViewBinder<KeyboardSelectModel, 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: KeyboardSelectModel
    ) {
        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.loadUrlImage(item.imageUrl, iconDefaultResId)
        holder.vName.text = item.name

        // 选中
        if (item.isSelect) {
            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)
    }
}