package kr.co.vividnext.sodalive.mypage.can.charge.iap

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.RecyclerView
import com.android.billingclient.api.ProductDetails
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.databinding.ItemCanChargeBinding
import kr.co.vividnext.sodalive.extensions.fontSpan

class CanChargeIapAdapter(
    private val onClick: (ProductDetails) -> Unit
) : RecyclerView.Adapter<CanChargeIapAdapter.ViewHolder>() {

    val items = mutableListOf<ProductDetails>()

    inner class ViewHolder(
        private val context: Context,
        private val binding: ItemCanChargeBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: ProductDetails) {
            binding.tvPrice.text = item.oneTimePurchaseOfferDetails?.formattedPrice

            val typeface = ResourcesCompat.getFont(context, R.font.gmarket_sans_medium)
            binding.tvTitle.text = item.name.fontSpan(
                typeface,
                "캔"
            )

            binding.root.setOnClickListener { onClick(item) }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
        parent.context,
        ItemCanChargeBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
    )

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount() = items.count()

    @SuppressLint("NotifyDataSetChanged")
    fun addItems(items: List<ProductDetails>) {
        this.items.addAll(items.sortedBy { it.description.toInt() })
        notifyDataSetChanged()
    }
}
