package com.base.browserwhite.ui.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.browserwhite.R
import com.base.browserwhite.bean.NewsBean
import com.base.browserwhite.databinding.ItemNewsBinding
import com.base.browserwhite.utils.KotlinExt.toFormatTime
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.XmlEx.inflate
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.chad.library.adapter4.BaseQuickAdapter

class NewsAdapter(
    val clickAction: (url: String) -> Unit
) : BaseQuickAdapter<NewsBean, NewsAdapter.NewsViewHolder>() {

    private val TAG = "NewsAdapter"


    inner class NewsViewHolder(view: View) : ViewHolder(view)


    override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): NewsViewHolder {
        return NewsViewHolder(R.layout.item_news.inflate(parent))
    }

    override fun onBindViewHolder(holder: NewsViewHolder, position: Int, item: NewsBean?) {
        LogEx.logDebug(TAG, "onBindViewHolder")
        if (item == null) {
            return
        }
        val binding = ItemNewsBinding.bind(holder.itemView)


        if (items.first() == item) {
            binding.ll.visibility = View.VISIBLE
        } else {
            binding.ll.visibility = View.GONE
        }

//        val bean = beanList[position]
        val context = holder.itemView.context
        Glide.with(context).load(item.orgImgPath).listener(object : RequestListener<Drawable> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<Drawable>,
                isFirstResource: Boolean
            ): Boolean {
                return true
            }

            override fun onResourceReady(
                resource: Drawable,
                model: Any,
                target: Target<Drawable>?,
                dataSource: DataSource,
                isFirstResource: Boolean
            ): Boolean {
                return false
            }

        }).centerCrop().into(binding.ivMedia)
        binding.tvTittle.text = item.headline
        runCatching {
            Glide.with(context).load(item.mediaIcon).into(binding.ivIcon)
        }
        binding.tvMediaName.text = item.mediaName
        binding.tvPublishTime.text = item.publishTime.toFormatTime()
        binding.root.setOnClickListener {
            clickAction.invoke(item.linkPath)
        }
    }

    fun getLastPageNumber(): Long? {
        return if (items.isEmpty()) {
            null
        } else {
            items.last().newsId
        }
    }
}