package com.casic.br.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.casic.br.R
import com.pengxh.kt.lite.extensions.convertColor

/**
 * 设备分类列表Adapter
 * */
class DeviceTypeAdapter(
    private val context: Context, private val titles: Array<String>
) : RecyclerView.Adapter<DeviceTypeAdapter.ItemViewHolder>() {

    private var layoutInflater: LayoutInflater = LayoutInflater.from(context)
    private var mPosition = 0

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ItemViewHolder(
        layoutInflater.inflate(R.layout.item_device_type_rv_l, parent, false)
    )

    override fun onBindViewHolder(
        holder: ItemViewHolder, @SuppressLint("RecyclerView") position: Int
    ) {
        holder.textView.text = titles[position]

        // 设置默认选择第一个
        if (mPosition != position) {
            holder.textView.setTextColor(R.color.mainTextColor.convertColor(context))
        } else if (mPosition == position) {
            holder.textView.setTextColor(R.color.mainThemeColor.convertColor(context))
        }

        holder.itemView.setOnClickListener {
            clickListener?.onItemClick(position)
            // 选中点击的位置
            mPosition = position
            notifyDataSetChanged()
        }
    }

    override fun getItemCount(): Int = titles.size

    private var clickListener: OnTypeItemClickListener? = null

    interface OnTypeItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setOnTypeItemClickListener(clickListener: OnTypeItemClickListener?) {
        this.clickListener = clickListener
    }

    class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val textView: TextView = itemView.findViewById(R.id.textView)
    }
}