package com.doverfuelingsolutions.issp.view.adapter

import android.graphics.Color
import android.view.View
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.RecyclerView
import com.doverfuelingsolutions.issp.DFSApplication
import com.doverfuelingsolutions.issp.R
import kotlinx.android.synthetic.main.adapter_choose_item.view.*

class ChooseListAdapter(private val chooseList: List<String>, private val handler: (item: String) -> Unit, private val chooseEffect: Boolean = false) :
    RecyclerView.Adapter<ChooseListAdapter.ChooseViewHolder>() {

    private var selectedIndex = 0

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChooseViewHolder {
        val view = View.inflate(parent.context, R.layout.adapter_choose_item, null)
        return ChooseViewHolder(view)
    }

    override fun onBindViewHolder(holder: ChooseViewHolder, position: Int) {
        holder.itemView.chooseItemView.text = chooseList[position]
        if (chooseEffect) {
            val color = if (!chooseEffect || selectedIndex == position)
                ResourcesCompat.getColor(DFSApplication.instance.applicationContext.resources, R.color.colorPrimary, null)
            else
                ResourcesCompat.getColor(DFSApplication.instance.applicationContext.resources, R.color.colorBBB, null)
            holder.itemView.chooseItemView.setBackgroundColor(color)
        }
        holder.itemView.chooseItemView.setOnClickListener {
            if (chooseEffect) {
                selectedIndex = position
                notifyDataSetChanged()
            }
            handler.invoke(chooseList[position])
        }
    }

    override fun getItemCount(): Int = chooseList.size

    class ChooseViewHolder(view: View) : RecyclerView.ViewHolder(view)
}