package com.gh.gamecenter.subject.tile

import android.content.Context
import android.graphics.Typeface
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import androidx.core.content.ContextCompat
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.toDrawable
import com.lightgame.adapter.BaseRecyclerAdapter

class SubjectTypeListAdapter(
    context: Context,
    private val mItemClickListener: (type: String) -> Unit,
    private val mGameType: List<String>
) : BaseRecyclerAdapter<SubjectTypeListAdapter.SubjectTypeViewHolder>(context) {

    private var mCurType = "全部"

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SubjectTypeViewHolder {
        return SubjectTypeViewHolder(mLayoutInflater.inflate(R.layout.subject_rows_label_item, parent, false))
    }

    override fun onBindViewHolder(holder: SubjectTypeViewHolder, position: Int) {
        holder.type.updateLayoutParams<ViewGroup.MarginLayoutParams> {
            width = ViewGroup.LayoutParams.MATCH_PARENT
        }
        holder.type.background = R.drawable.subject_label_background_style.toDrawable(mContext)
        holder.type.setTextColor(ContextCompat.getColorStateList(mContext, R.color.subject_label_text_style))
        holder.type.text = mGameType[position]

        val isChecked = !TextUtils.isEmpty(mCurType) && mCurType == mGameType[position]
        holder.type.isChecked = isChecked
        holder.type.setTypeface(Typeface.DEFAULT, if (isChecked) Typeface.BOLD else Typeface.NORMAL)

        holder.type.setOnClickListener {
            if (holder.bindingAdapterPosition == -1) return@setOnClickListener

            mCurType = mGameType[holder.bindingAdapterPosition]
            mItemClickListener.invoke(mGameType[holder.bindingAdapterPosition])
            notifyDataSetChanged()
        }
    }

    override fun getItemCount(): Int {
        return mGameType.size
    }

    inner class SubjectTypeViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val type: CheckedTextView by lazy { itemView.findViewById(R.id.label) }
    }
}