package com.paperapp.lenscape.tools

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView

class TagMoveHelper : LinearSnapHelper() {

    private var recyclerView: RecyclerView? = null

    override fun attachToRecyclerView(recyclerView: RecyclerView?) {
        super.attachToRecyclerView(recyclerView)
        this.recyclerView = recyclerView
    }

    override fun calculateDistanceToFinalSnap(
        layoutManager: RecyclerView.LayoutManager,
        targetView: View
    ): IntArray {
        val out = IntArray(2)
        if (layoutManager.canScrollHorizontally()) {
            out[0] = calculateDistanceToCenter(targetView, layoutManager)
        } else {
            out[0] = 0
        }

        if (layoutManager.canScrollVertically()) {
            out[1] = calculateDistanceToCenter(targetView, layoutManager)
        } else {
            out[1] = 0
        }
        return out
    }

    override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? {
        return findCenterView(layoutManager)
    }

    private fun calculateDistanceToCenter(targetView: View, layoutManager: RecyclerView.LayoutManager): Int {
        if (layoutManager.canScrollHorizontally()) {
            val centerX = (layoutManager.width / 2)
            val targetCenterX = (targetView.left + targetView.right) / 2
            return targetCenterX - centerX
        }
        return 0
    }

    private fun findCenterView(layoutManager: RecyclerView.LayoutManager): View? {
        if (layoutManager !is LinearLayoutManager) return null

        val centerX = layoutManager.width / 2
        var minDistance = Int.MAX_VALUE
        var centerView: View? = null

        for (i in 0 until layoutManager.childCount) {
            val child = layoutManager.getChildAt(i) ?: continue
            val childCenterX = (child.left + child.right) / 2
            val distance = Math.abs(childCenterX - centerX)

            if (distance < minDistance) {
                minDistance = distance
                centerView = child
            }
        }

        return centerView
    }
}