package com.gh.gamecenter.home.custom.ui

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gh.gamecenter.R
import com.gh.gamecenter.common.utils.goneIf
import com.gh.gamecenter.common.utils.visibleIf
import com.gh.gamecenter.databinding.RecyclerRecommendCardCustomBinding
import com.gh.gamecenter.home.custom.adapter.RecommendCardAdapter
import com.gh.gamecenter.home.custom.model.CustomPageData

class RecommendCardUi(
    private val binding: RecyclerRecommendCardCustomBinding,
    private val listener: OnRecommendCardEventListener
) {

    private val context: Context
        get() = binding.root.context

    private val adapter by lazy {
        RecommendCardAdapter(context, listener)
    }

    fun bind(rightTop: String, title: String, subTitle: String, recommendCards: List<CustomPageData.RecommendCard>) {
        if (binding.rvCards.adapter == null) {
            binding.rvCards.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            binding.rvCards.adapter = adapter
        }
        binding.tvRight.goneIf(rightTop.isBlank()) {
            binding.tvRight.setText(R.string.custom_home_text_all)
        }
        binding.tvTitle.goneIf(title.isBlank()) {
            binding.tvTitle.text = title
        }
        binding.tvSubTitle.goneIf(subTitle.isBlank()) {
            binding.tvSubTitle.text = subTitle
        }
        adapter.submitList(recommendCards)

        binding.tvRight.setOnClickListener {
            listener.onAllClick()
        }

        binding.vBackground.setBackgroundResource(R.drawable.bg_img_recommend_card)

        binding.root.post {
            if (binding.tvSubTitle.visibility == View.VISIBLE) {
                val ellipsisStart = binding.tvSubTitle.layout?.getEllipsisStart(0) ?: 0
                binding.tvSubTitle.visibleIf(ellipsisStart == 0)
            }
        }
    }

    interface OnRecommendCardEventListener {
        fun onItemClick(childPosition: Int, card: CustomPageData.RecommendCard)

        fun onAllClick()
    }
}