package com.yidianling.tests.list.view.adapter

import android.content.Context
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.yidianling.tests.R
import com.yidianling.tests.list.model.bean.CategotyPopItem
import kotlinx.android.synthetic.main.tests_item_tab_pop_sort.view.*

/**
 * Created by zqk on 17-9-20.
 */
class CategoryConditionRecyclerViewAdapter(private val context: Context,
                                           private val sortItems: ArrayList<CategotyPopItem>,
                                           private val onItemSelectedListener: OnItemSelectedListener) : RecyclerView.Adapter<CategoryConditionRecyclerViewAdapter.ViewHolder>() {

    override fun getItemCount(): Int = sortItems.size
    var lastSelectView : TextView ?= null
    var lastSelectText : String ?= null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = LayoutInflater.from(context).inflate(R.layout.tests_item_tab_pop_sort, parent, false)
        return ViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = sortItems[position]
        holder.tvSort.text = item.value
        holder.tvSort.setTextColor(ContextCompat.getColor(context, R.color.platform_color_242424))
        if (!TextUtils.isEmpty(lastSelectText) && item.value.equals(lastSelectText) && position!=0){
            holder.tvSort.setTextColor(ContextCompat.getColor(context, R.color.platform_main_theme))
            lastSelectView = holder.tvSort
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val tvSort = itemView.tvSort!!

        init {
            itemView.setOnClickListener {

                lastSelectView?.setTextColor(ContextCompat.getColor(context, R.color.platform_color_242424))
                if (adapterPosition != 0){
                    tvSort.setTextColor(ContextCompat.getColor(context, R.color.platform_main_theme))
                }

                if (adapterPosition != RecyclerView.NO_POSITION){
                    onItemSelectedListener.onSortItemSelected(sortItems[adapterPosition])
                }
                lastSelectView = tvSort
            }
        }
    }


    interface OnItemSelectedListener {
        fun onSortItemSelected(sortItem: CategotyPopItem)
    }
}