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

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import coil.load
import com.seatel.mobilehall.R
import com.seatel.mobilehall.databinding.ItemHomeImageSliderBinding
import com.seatel.mobilehall.ui.home.model.BannersModel
import com.seatel.mobilehall.ui.login.activity.TermsAndConditionsActivity
import com.smarteist.autoimageslider.SliderViewAdapter

class HomeImageSliderAdapter(
    var context: Context,
    private var onActionLink: (String) -> Unit,
) : SliderViewAdapter<HomeImageSliderAdapter.SliderAdapterVH>() {

    private var mSliderItems = mutableListOf<BannersModel>()

    fun renewItems(sliderItems: MutableList<BannersModel>) {
        mSliderItems = sliderItems
        notifyDataSetChanged()
    }

    fun deleteItem(position: Int) {
        mSliderItems.removeAt(position)
        notifyDataSetChanged()
    }

    fun addItem(sliderItem: List<BannersModel>) {
        mSliderItems = sliderItem.toMutableList()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup): SliderAdapterVH {

        val binding =
            ItemHomeImageSliderBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return SliderAdapterVH(binding)

    }

    override fun onBindViewHolder(viewHolder: SliderAdapterVH, position: Int) {
        val sliderItem = mSliderItems[position]

        // Load image with Coil
        viewHolder.view.ivAutoImageSlider.load(sliderItem.imageUrl) {
            crossfade(true)
            placeholder(R.drawable.bg_round_gray_section)
            error(R.drawable.bg_round_gray_section)
        }
        viewHolder.itemView.setOnClickListener(View.OnClickListener {

            when (sliderItem.actionType) {
                "in-app" -> {
                    TermsAndConditionsActivity.launch(
                        context, sliderItem.imageUrl!!
                    )
                }

                "out-app" -> {
                    sliderItem.url?.let { url ->
                        onActionLink.invoke(url)
                    }

                }
            }


        })
    }

    override fun getCount(): Int {
        //slider view count could be dynamic size
        return mSliderItems.size
    }

    class SliderAdapterVH(val view: ItemHomeImageSliderBinding) : ViewHolder(view.root)
}