package com.base.browserwhite.ui.views.itemtouch

import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.base.browserwhite.ui.adapter.WebsiteAdapter

class MyItemTouchHelperCallBack : ItemTouchHelper.Callback() {

    private val TAG = "MyItemTouchHelperCallBack"

    /**
     * 设置拖拽和item滑动的可支持方向
     */
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {

        if (!(viewHolder as WebsiteAdapter.WebSiteViewHolder).canDrag) {
            return makeMovementFlags(ItemTouchHelper.ACTION_STATE_IDLE, 0) // 不允许拖动
        }


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

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

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

        //todo 更新recycleView中数据的位置
        (recyclerView.adapter as WebsiteAdapter).changeBeanPosition(viewHolder.layoutPosition, target.layoutPosition)
        return true
    }

    /**
     * 侧滑回调
     */
    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) = Unit

    /**
     * 长点击拖动
     */
    override fun isLongPressDragEnabled() = true

    /**
     * 可结束拖动
     */
    override fun canDropOver(
        recyclerView: RecyclerView,
        current: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        return (target as WebsiteAdapter.WebSiteViewHolder).canDrag
    }
}