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.MediaBean
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, position: Int) {
        val log = "position=${holder.position} " +
                "position=${holder.bindingAdapterPosition} " +
                "position=${holder.absoluteAdapterPosition} " +
                "position=${holder.layoutPosition}"
        LogEx.logDebug(
            TAG, log
        )
        val binding = ItemNewsBinding.bind(holder.itemView)
        val bean = beanList[holder.position]
        val context = holder.itemView.context
        Glide.with(context).load(bean.orgImgPath).listener(object : RequestListener<Drawable> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<Drawable>,
                isFirstResource: Boolean
            ): Boolean {
                LogEx.logDebug(TAG, "onLoadFailed $log")
//                beanList.remove(bean)
                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()
        bean.isBind = true
    }

    @SuppressLint("NotifyDataSetChanged")
    fun loadMore(
        categoryId: Int = 0,
        errorCallBack: (() -> Unit)? = null,
        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,
            errorCallBack = {
                errorCallBack?.invoke()
            })
        {
            beanList.addAll(it)
            if (beanList.size > 150) {
                val item100 = beanList.subList(0, 100)
                beanList.removeAll(item100.toSet())
            }
            lifecycleScope.launch(Dispatchers.Main) {
                this@NewsAdapter.notifyItemInserted(position)
                delay(2000)
                callBack?.invoke()
            }
        }
    }


}