package com.adealink.weparty.profile.edit.comp

import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.adealink.frame.log.Log
import com.adealink.weparty.profile.edit.adapter.AddPhotoItemViewBinder


class PhotoWallItemTouchHelperCallback(
    private var isLongPressDragEnabled: (() -> Boolean)?,
    private var dragCallback: OnItemDragCallback?,
) : ItemTouchHelper.Callback() {

    private var startDragPosition = -1

    override fun isLongPressDragEnabled(): Boolean {
        Log.d(TAG, "isLongPressDragEnabled")
        return isLongPressDragEnabled?.invoke() ?: true
    }

    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
    ): Int {
        Log.d(TAG, "getMovementFlags, vh:$viewHolder")
        if (viewHolder is AddPhotoItemViewBinder.ViewHolder) {
            //"添加图片"不能拖动
            return makeMovementFlags(0, 0)
        }
        val dragFlags =
            ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
        return makeMovementFlags(dragFlags, 0)
    }

    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder,
    ): Boolean {
        Log.d(
            TAG,
            "onMove: originPosition: ${viewHolder.bindingAdapterPosition}, targetPosition:${target.bindingAdapterPosition}"
        )
        dragCallback?.onMoved(viewHolder.bindingAdapterPosition, target.bindingAdapterPosition)
        return true
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        Log.d(TAG, "onSwiped: direction:${direction}")
    }

    override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
        Log.d(TAG, "onSelectedChanged:$viewHolder, $actionState")
        if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {
            startDragPosition = viewHolder?.bindingAdapterPosition ?: -1
            Log.d(TAG, "start drag position:$startDragPosition")
            dragCallback?.onDragStart()
        }
    }

    override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
        Log.d(TAG, "clearView")
        viewHolder.itemView.isClickable = true
        if (viewHolder.bindingAdapterPosition != startDragPosition) {
            dragCallback?.onDragEndByPositionChanged()
        } else {
            dragCallback?.onDragEndByNoChanged()
        }
    }

    interface OnItemDragCallback {
        fun onDragStart() {}
        fun onMoved(fromPosition: Int, toPosition: Int) {}
        fun onDragEndByPositionChanged() {}
        fun onDragEndByNoChanged() {}
    }

    companion object {
        private const val TAG = "PhotoWallItemTouchHelperCallback"
    }
}