package com.mobiuz.app.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 com.mobiuz.app.databinding.ItemActionBinding
import com.mobiuz.app.dev.model.UssdData
import com.mobiuz.app.dev.ui.global.ButtonClick
import com.mobiuz.app.dev.utils.extensions.SingleBlock
import com.mobiuz.app.dev.utils.extensions.getCurrentName

class ActionAdapter(val lang: String) : RecyclerView.Adapter<ActionAdapter.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.getCurrentName(lang)
                val des = d.short_description.getCurrentName(lang)
                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
    }

}