package com.base.browserwhite.ui.adapter

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.recyclerview.widget.RecyclerView
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.NewsUtils
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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class NewsAdapter(
    private val lifecycleScope: LifecycleCoroutineScope
) : RecyclerView.Adapter<NewsAdapter.NewsViewHolder>() {

    private val TAG = "NewsAdapter"
    private val beanList = arrayListOf<NewsBean>()

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

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

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

    override fun onBindViewHolder(holder: NewsViewHolder, @SuppressLint("RecyclerView") position: Int) {
        val binding = ItemNewsBinding.bind(holder.itemView)
        val bean = beanList[holder.absoluteAdapterPosition]
        val context = holder.itemView.context
        runCatching {
            Glide.with(context).load(bean.orgImgPath).listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>,
                    isFirstResource: Boolean
                ): Boolean {
                    beanList.remove(bean)
                    notifyItemRemoved(position)
                    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 = bean.headline
        runCatching {
            Glide.with(context).load(bean.mediaIcon).into(binding.ivIcon)
        }
        binding.tvMediaName.text = bean.mediaName
        binding.tvPublishTime.text = bean.publishTime.toFormatTime()
    }

    fun loadMore(categoryId: Int = 0, callBack: (() -> Unit)? = null) {
        val position = beanList.size
        val last = if (beanList.isEmpty()) null else beanList.last()
        LogEx.logDebug(TAG, "newsId=${last?.newsId}")
        NewsUtils.requestNews(categoryId, last?.newsId) {
            beanList.addAll(it)
            lifecycleScope.launch(Dispatchers.Main) {
                this@NewsAdapter.notifyItemInserted(position)
                delay(1000)
                callBack?.invoke()
            }
        }
    }


}