package com.base.pdfreaderallpdfreader.ui.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.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.bean.DocumentBean
import com.base.pdfreaderallpdfreader.databinding.ItemPdfMergeBinding
import com.base.pdfreaderallpdfreader.utils.KotlinExt.toFormatSize
import com.base.pdfreaderallpdfreader.utils.KotlinExt.toFormatTime4
import com.base.pdfreaderallpdfreader.utils.LogEx
import com.base.pdfreaderallpdfreader.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.r_pdf)
        } else {
            binding.iv.setImageResource(R.mipmap.rv_pdf_lock)
        }

        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))
    }


}