package es.verdnatura.presentation.view.feature.pasillero.adapter

import android.os.Build
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import es.verdnatura.BR
import es.verdnatura.R
import es.verdnatura.databinding.ItemMainMenuBinding
import es.verdnatura.databinding.ItemPasillerosMainMenuBinding
import es.verdnatura.domain.toast
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO

class PasillerosAdapter(
    private val items: List<PasillerosItemVO>,
    private val onPasillerosItemClickListener: OnPasillerosItemClickListener,
    private val isMenuInit: Boolean
) : RecyclerView.Adapter<PasillerosAdapter.PasillerosItemHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PasillerosItemHolder {
        val layoutInflater = LayoutInflater.from(parent.context)
        val binding: ViewDataBinding =
            DataBindingUtil.inflate(layoutInflater, viewType, parent, false)
        return PasillerosItemHolder(binding)
    }

    override fun getItemViewType(position: Int) =
        if (isMenuInit) R.layout.item_main_menu else R.layout.item_pasilleros_main_menu

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: PasillerosItemHolder, position: Int) {
        holder.bind(items[position])
        holder.binding.root.setOnClickListener {
            onPasillerosItemClickListener.onPasillerosItemClickListener(items[position], "")
        }
    }

    inner class PasillerosItemHolder(val binding: ViewDataBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: PasillerosItemVO) {
            binding.setVariable(BR.item, item)
            binding.setVariable(BR.title, binding.root.context.getString(item.title!!))

            val itemImage = if (isMenuInit) {
                (binding as ItemMainMenuBinding).itemImage
            } else {
                (binding as ItemPasillerosMainMenuBinding).itemImage
            }

            try {
                itemImage.setImageResource(item.iconResource)
            } catch (exception: Exception) {
                exception.toast(binding.root.context)
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                itemImage.tooltipText = binding.root.context.getString(item.description!!)
            }
        }
    }
}