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.ItemActionBinding
import uz.mobiuz.mobiservice.dev.model.UssdData
import uz.mobiuz.mobiservice.dev.ui.global.ButtonClick
import uz.mobiuz.mobiservice.dev.utils.extensions.SingleBlock

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

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

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VHolder {
        return VHolder(ItemActionBinding.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: ItemActionBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(position: Int) {
            val d = list[position]
            binding.apply {
                title.text = d.title.getTranslated()
                val des = d.short_description.getTranslated()
                description.text = des
                description.isVisible = des.isNotEmpty()
                code.text = d.code
                cardView.setOnClickListener(object : ButtonClick() {
                    override fun onSingleClick(v: View?) {
                        listener?.invoke(d)
                    }
                })
            }
        }
    }

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


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

}