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

import android.annotation.SuppressLint
import android.content.Context
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.base.pdfviewerscannerwhite.R
import com.base.pdfviewerscannerwhite.bean.DocumentBean
import com.base.pdfviewerscannerwhite.databinding.ItemPdfMergeBinding
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatSize
import com.base.pdfviewerscannerwhite.utils.KotlinExt.toFormatTime4
import com.base.pdfviewerscannerwhite.utils.LogEx
import com.base.pdfviewerscannerwhite.utils.XmlEx.inflate
import com.chad.library.adapter4.BaseQuickAdapter
import java.io.File


class PdfMergeAdapter(
    val itemTouchHelper: ItemTouchHelper,
    val callBack: PdfMergeItemTouchHelperCallBack
) : BaseQuickAdapter<DocumentBean, PdfMergeAdapter.PdfMergeViewHolder>() {


    private val TAG = "PdfMergeAdapter"
    var removeAction: ((item: DocumentBean) -> Unit)? = null

    inner class PdfMergeViewHolder(view: View) : RecyclerView.ViewHolder(view)

    @SuppressLint("SetTextI18n", "ClickableViewAccessibility")
    override fun onBindViewHolder(holder: PdfMergeViewHolder, position: Int, item: DocumentBean?) {
        if (item == null) return
        val binding = ItemPdfMergeBinding.bind(holder.itemView)
        val file = File(item.path)
        binding.tvName.text = file.name
        binding.tvInfo.text = file.lastModified().toFormatTime4() + " " + file.length().toFormatSize()
        if (item.state==0){
            binding.iv.setImageResource(R.mipmap.h_pdfiocn)
        }else{
            binding.iv.setImageResource(R.mipmap.suoding)
        }

        binding.flClose.setOnClickListener {
            remove(item)
            removeAction?.invoke(item)
        }

        binding.ivMove.setOnTouchListener(object : View.OnTouchListener {
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                if (event?.action == MotionEvent.ACTION_DOWN) {
                    callBack.enableLongPress = true
                    LogEx.logDebug(TAG, "ACTION_DOWN ${System.currentTimeMillis()}")
                    // 长按时启动拖动
                    itemTouchHelper.startDrag(holder)
                    return true
                }
                return false
            }
        })
    }

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


}