package com.waytous.anticollision.utils

import android.graphics.Rect
import android.view.TouchDelegate
import android.view.View
import android.view.ViewGroup
import androidx.databinding.BindingAdapter
import com.blankj.utilcode.util.SizeUtils

@BindingAdapter("expandTouchArea")
fun expandTouchArea(view: View, size: String) {
    view.postDelayed({
        val bounds = Rect()
        view.getHitRect(bounds)
        var left = 0
        var top = 0
        var right = 0
        var bottom = 0
        /*
        *  size 举例 `2` or `2 4` or `2 4 6 8`
         */
        val mSize = size.trim()
        val ss = mSize.split(" ")
        when (ss.size) {
            1 -> {
                val sdp = SizeUtils.dp2px(((ss[0].toIntOrNull() ?: 0).toFloat()))
                left = sdp
                top = sdp
                right = sdp
                bottom = sdp
            }
            2 -> {
                val sdp = SizeUtils.dp2px(((ss[0].toIntOrNull() ?: 0).toFloat()))
                val sdp1 = SizeUtils.dp2px(((ss[1].toIntOrNull() ?: 0).toFloat()))
                left = sdp
                top = sdp1
                right = sdp
                bottom = sdp1
            }
            4 -> {
                left = (ss[0].toIntOrNull() ?: 0)
                top = SizeUtils.dp2px(((ss[1].toIntOrNull() ?: 0).toFloat()))
                right = SizeUtils.dp2px(((ss[2].toIntOrNull() ?: 0).toFloat()))
                bottom = SizeUtils.dp2px(((ss[3].toIntOrNull() ?: 0).toFloat()))
            }
            else -> {
                return@postDelayed
            }
        }
        bounds.left -= left
        bounds.top -= top
        bounds.right += right
        bounds.bottom += bottom
        val mTouchDelegate = TouchDelegate(bounds, view);
        val p = view.parent
        if (p is ViewGroup) {
            p.touchDelegate = mTouchDelegate;
        }
    }, 100)
}