package com.base.pdfviewerscannerwhite.ui.document.pdf

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.PdfPageBean
import com.base.pdfviewerscannerwhite.databinding.ItemPdfPagerBinding
import com.base.pdfviewerscannerwhite.utils.PdfUtils
import com.base.pdfviewerscannerwhite.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit


class PdfPagerAdapter(val pdfPath: String) : BaseQuickAdapter<PdfPageBean, PdfPagerAdapter.PdfPagerViewHolder>() {

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

    var corePoolSize = 4 // 核心线程数
    var maximumPoolSize = 10 // 最大线程数
    var keepAliveTime: Long = 120 // 非核心线程空闲存活时间
    var threadPoolExecutor = ThreadPoolExecutor(
        corePoolSize,
        maximumPoolSize,
        keepAliveTime,
        TimeUnit.SECONDS,
        LinkedBlockingQueue()
    )

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: PdfPagerViewHolder, position: Int, item: PdfPageBean?) {
        if (item == null) return
        val binding = ItemPdfPagerBinding.bind(holder.itemView)
        val context = holder.itemView.context
        binding.tvPagerIndex.isSelected = item.isSelect
        binding.tvPagerIndex.text = (item.pageIndex + 1).toString()
        binding.flBorder.isSelected = item.isSelect
        item.pageDrawable?.let {
            binding.ivPager.setImageDrawable(it)
        }
        loadPagerDrawable(context, binding, item)
    }

    private fun loadPagerDrawable(context: Context, binding: ItemPdfPagerBinding, item: PdfPageBean) {
        threadPoolExecutor.execute {
            runCatching {
                val drawable = PdfUtils.getPdfDrawablePage(context, pdfPath, item.pageIndex)
                item.pageDrawable = drawable
                // 任务代码
                binding.root.post {
                    item.pageDrawable?.let {
                        binding.ivPager.setImageDrawable(it)
                    }
                }
            }

        }
    }

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