package com.yidianling.consultant.adapter

import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.yidianling.consultant.R
import com.yidianling.consultant.model.bean.CateItem
import kotlinx.android.synthetic.main.consultant_item_subject.view.*

/**
 * 主题Recycler适配器
 * Created by zqk on 17-9-19.
 */
class CategoryRecyclerViewAdapter(private val context: Context, private val categories: ArrayList<CateItem>, private val selectedCategories: ArrayList<CateItem>) : RecyclerView.Adapter<CategoryRecyclerViewAdapter.ViewHolder>() {

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if (holder != null) {
            val category = categories[position]
            holder.tvSubjectName.text = categories[position].cateName
            holder.tvSubjectName.isSelected = selectedCategories.contains(category)
        }
    }

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

    override fun getItemCount(): Int = categories.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvSubjectName: TextView = itemView.tv_sort_name

        init {
            itemView.setOnClickListener {
                if (adapterPosition != RecyclerView.NO_POSITION) {
                    val subject = categories[adapterPosition]
                    when {
                        adapterPosition == 0 -> {
                            selectedCategories.clear()
                            selectedCategories.add(subject)
                            notifyDataSetChanged()
                        }
                        selectedCategories.contains(subject) -> {
                            selectedCategories.remove(subject)
                            notifyItemChanged(adapterPosition)
                            if (selectedCategories.size == 0) {
                                selectedCategories.add(categories[0])
                                notifyItemChanged(0)
                            }
                        }
                        else -> {
                            selectedCategories.add(subject)
                            notifyItemChanged(adapterPosition)
                            if (selectedCategories.contains(categories[0])) {
                                selectedCategories.remove(categories[0])
                                notifyItemChanged(0)
                            }
                        }
                    }
                }
            }
        }

    }

}