package com.remax.visualnovel.extension

import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import kotlin.math.abs

/**
 * Created by HJW on 2022/11/16
 */

/**
 * 搜索页的RecyclerView 点击无子view的地方回调
 */
fun RecyclerView.setSearchClosePageEvent(nullViewCallback: () -> Unit) {
    addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
        var dx = 0f
        var dy = 0f
        override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
            when (e.action) {
                MotionEvent.ACTION_MOVE -> {
                }

                MotionEvent.ACTION_UP -> {
                    val x = dx - e.x
                    if (abs(x) < 30) {
                        val view = rv.findChildViewUnder(e.x, e.y)
                        if (view == null) {
                            nullViewCallback.invoke()
                        }
                    }
                }

                MotionEvent.ACTION_DOWN -> {
                    dx = e.x
                    dy = e.y
                }
            }
            return false
        }

        override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
        }

        override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
        }
    })
}

fun SmartRefreshLayout.autoRefreshList(animationOnly: Boolean = false) {
    autoRefresh(400, 300, 1f, animationOnly)
}
