package uz.mobiuz.mobiservice.dev.ui.service

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import uz.mobiuz.mobiservice.dev.databinding.ItemServiceBinding
import uz.mobiuz.mobiservice.dev.model.ServiceData
import uz.mobiuz.mobiservice.dev.ui.global.ButtonClick
import uz.mobiuz.mobiservice.dev.utils.extensions.SingleBlock

class ServicesAdapter : RecyclerView.Adapter<ServicesAdapter.VHolder>() {

    private val list: ArrayList<ServiceData> by lazy { ArrayList() }
    private var listener: SingleBlock<ServiceData>? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VHolder {
        return VHolder(ItemServiceBinding.inflate(LayoutInflater.from(parent.context)))
    }

    override fun onBindViewHolder(holder: VHolder, position: Int) = holder.bind(position)
    override fun getItemCount() = list.size

    inner class VHolder(private val binding: ItemServiceBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(position: Int) {
            val d = list[position]
            binding.apply {

                txtTitle.text = d.title.getTranslated()
                val des = d.short_description.getTranslated()
                txtDescription.text = des
                txtDescription.isVisible = des.isNotEmpty()
                cardView.setOnClickListener(object : ButtonClick() {
                    override fun onSingleClick(v: View?) {
                        listener?.invoke(d)
                    }
                })
            }
        }
    }

    fun submitList(ls: List<ServiceData>) {
        list.clear()
        list.addAll(ls)
        notifyDataSetChanged()
    }


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

}