package com.seatel.mobilehall.ui.home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.seatel.mobilehall.databinding.ItemHomeBannerBinding
import com.seatel.mobilehall.ui.home.model.BannersModel
import com.seatel.mobilehall.ui.login.activity.TermsAndConditionsActivity

class ImageSliderAdapter(
    private val banners: List<BannersModel>,
    private var onActionLink: (String) -> Unit,
) : RecyclerView.Adapter<ImageSliderAdapter.SliderVH>() {

    private val newList: List<BannersModel> =
        listOf(banners.last()) + banners + listOf(banners.first())

    class SliderVH(val binding: ItemHomeBannerBinding) : RecyclerView.ViewHolder(binding.root)

    lateinit var binding: ItemHomeBannerBinding
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): ImageSliderAdapter.SliderVH {
        val binding = ItemHomeBannerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return SliderVH(binding)
    }

    override fun onBindViewHolder(holder: ImageSliderAdapter.SliderVH, position: Int) {
        val banner = newList[position]
        Glide.with(holder.itemView.context).load(banner.imageUrl).into(holder.binding.imageView)
        holder.itemView.setOnClickListener(View.OnClickListener {
            when (banner.actionType) {
                "in-app" -> {
                    TermsAndConditionsActivity.launch(
                        holder.itemView.context, banner.imageUrl!!
                    )
                }
                "out-app" -> {
                    banner.url?.let { url ->
                        onActionLink.invoke(url)
                    }
                }
            }
        })
    }

    override fun getItemCount(): Int {
        return newList.size
    }
}