package uz.mobiuz.mobiservice.dev.ui.home

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.load
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.ItemHomeBinding
import uz.mobiuz.mobiservice.dev.network.model.Events
import uz.mobiuz.mobiservice.dev.ui.global.ButtonClick
import uz.mobiuz.mobiservice.dev.utils.extensions.SingleBlock

class SliderAdapter : RecyclerView.Adapter<SliderAdapter.SliderViewHolder>() {

    private var listener: SingleBlock<Events>? = null
    private val sliderItems: ArrayList<Events> = ArrayList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SliderViewHolder {
        return SliderViewHolder(
            ItemHomeBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun onBindViewHolder(holder: SliderViewHolder, position: Int) = holder.onBind(position)

    override fun getItemCount(): Int = sliderItems.size

    inner class SliderViewHolder(val view: ItemHomeBinding) : RecyclerView.ViewHolder(view.root) {

        fun onBind(position: Int) {
            val d = sliderItems[position]
            view.apply {
                imageSlider.load(d.image) {
                    error(R.drawable.ic_placeholder)
                }
                btnSeeMore.setOnClickListener(object : ButtonClick() {
                    override fun onSingleClick(v: View?) {
                        listener?.invoke(d)
                    }
                })

            }
        }

    }

    fun setOnClickListener(block: SingleBlock<Events>) {
        listener = block
    }

    fun submitList(ls: List<Events>) {
        sliderItems.clear()
        sliderItems.addAll(ls)
        notifyDataSetChanged()
    }
}