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

import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.base.pdfviewerscannerwhite.utils.LogEx

class PdfMergeItemTouchHelperCallBack : ItemTouchHelper.Callback() {

    var changeListOrder: ((olderPosition: Int, newPosition: Int) -> Unit)? = null

    var enableLongPress: Boolean = false

    private val TAG = "PdfMergeItemTouchHelperCallBack"
    override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {

        //支持上下左右拖动
//        ACTION_STATE_IDLE item默认滑动方向
        return makeMovementFlags(
            ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.START or ItemTouchHelper.END,
            ItemTouchHelper.ACTION_STATE_IDLE
        )
        // 禁用默认的拖动和滑动
//        return makeMovementFlags(0, 0);

    }

    /**
     * 拖拽结束后（手指抬起）会回调的方法
     */
    override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {

        //更新item holder对应位置
        recyclerView.adapter?.notifyItemMoved(
            viewHolder.adapterPosition,
            target.adapterPosition
        )

        changeListOrder?.invoke(viewHolder.layoutPosition, target.layoutPosition)
        enableLongPress = false
        return true
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) = Unit


    override fun isLongPressDragEnabled(): Boolean {
        LogEx.logDebug(TAG, "isLongPressDragEnabled $enableLongPress ${System.currentTimeMillis()}")
        return enableLongPress
    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        super.onSelectedChanged(viewHolder, actionState)
        if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
            // 当没有动作时，取消拖动状态
            viewHolder?.itemView?.setPressed(false)
        } else if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            // 当滑动时，设置拖动状态
            viewHolder?.itemView?.setPressed(true)
        }
    }

}