package cn.muchinfo.rma.view.autoWidget

import android.graphics.Rect
import android.os.SystemClock
import android.view.TouchDelegate
import android.view.View
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.TimeUtils
import com.jakewharton.rxbinding2.view.RxView
import java.util.concurrent.TimeUnit

fun Boolean?.trans2Visibility(default: Int = View.GONE): Int {
    if (this == null) {
        return default
    }
    return if (this) {
        View.VISIBLE
    } else {
        View.GONE
    }
}

/**
 * 防止重复点击
 */
fun View.onThrottleFirstClick(duration: Long = 1000, timeUnit: TimeUnit = TimeUnit.MILLISECONDS, l: ((v: android.view.View?) -> Unit)? = null) {
    RxView.clicks(this)
            .throttleFirst(duration, timeUnit)
            .subscribe {
                l?.invoke(this)
            }
}

/**
 * 防止重复点击
 */
fun View.onThrottleShortFirstClick(duration: Long = 100, timeUnit: TimeUnit = TimeUnit.MILLISECONDS, l: ((v: android.view.View?) -> Unit)? = null) {
    RxView.clicks(this)
            .throttleFirst(duration, timeUnit)
            .subscribe {
                l?.invoke(this)
            }

}


fun <T : View> T.widthProcent(procent: Int): Int =
    ScreenUtils.getScreenWidth().toFloat().times(procent.toFloat() / 100).toInt()

/**
 * 设置多次点击
 */
fun View.multiClick(multiTime: Int = 2, block: (() -> Unit)? = null) {
    val clickArray = LongArray(multiTime)
    RxView.clicks(this)
            .subscribe {
                System.arraycopy(clickArray, 1, clickArray, 0, clickArray.size.minus(1))
                val uptimeMillis = SystemClock.uptimeMillis()
                clickArray[clickArray.lastIndex] = uptimeMillis
                if (clickArray.first() >= uptimeMillis.minus(2000)) {
                    block?.invoke()
                    clickArray.fill(0)
                }
            }
}

/**
 * 扩大View的触摸和点击响应范围,最大不超过其父View范围
 */
fun View.expandViewTouchDelegate(left: Int, top: Int, right: Int, bottom: Int) {
    post {
        if (View::class.java.isInstance(parent)) {
            val rect = Rect()
            isEnabled = true
            getHitRect(rect)
            rect.top -= top
            rect.bottom += bottom
            rect.left -= left
            rect.right += right
            (parent as? View)?.touchDelegate = TouchDelegate(rect, this)
        }
    }
}

fun View.setPaddingAuto(paddingLeftAuto: Number? = null, paddingTopAuto: Number? = null, paddingRightAuto: Number? = null, paddingBottomAuto: Number? = null) {
    setPadding(
            paddingLeftAuto?.let { autoSize(it) } ?: paddingLeft,
            paddingTopAuto?.let { autoSize(it) } ?: paddingTop,
            paddingRightAuto?.let { autoSize(it) } ?: paddingRight,
            paddingBottomAuto?.let { autoSize(it) } ?: paddingBottom
    )
}