package xn.hxp.utils

import android.view.View
import android.widget.Button

class ButtonDebouncer {
    companion object {
        private const val DEFAULT_DEBOUNCE_TIME = 300L // 默认防抖时间

        fun setDebouncedOnClickListener(
            button: Button,
            debounceTime: Long = DEFAULT_DEBOUNCE_TIME,
            onClickListener: View.OnClickListener
        ) {
            val debouncedOnClickListener = DebouncedOnClickListener(debounceTime, onClickListener)
            button.setOnClickListener(debouncedOnClickListener)
        }
    }

    private class DebouncedOnClickListener(
        private val debounceTime: Long,
        private val onClickListener: View.OnClickListener
    ) : View.OnClickListener {
        private var lastClickTime: Long = 0

        override fun onClick(v: View) {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastClickTime >= debounceTime) {
                onClickListener.onClick(v)
            }
            lastClickTime = currentTime
        }
    }
}