package com.yidian.bcommon.extensions

import android.os.SystemClock
import android.view.View
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat

/**
 * 按钮点击防抖
 */
fun View?.clickAntiShake(intervalMillis: Long = 300, listener: (View) -> Unit) {
  // 最近一次点击的时间
  var lastClickTime: Long = 0
  this?.setOnClickListener {
    // 自启动以来的毫秒数，包括在睡眠中花费的时间
    val currentTime = SystemClock.elapsedRealtime()
    if (currentTime - lastClickTime >= intervalMillis) {
      listener.invoke(it)
      lastClickTime = currentTime
    }
  }
}

fun View.hide() {
  this.visibility = View.GONE
}

fun View.show() {
  this.visibility = View.VISIBLE
}

fun View.toggleVisibility() {
  if (this.visibility == View.GONE) {
    this.show()
  } else {
    this.hide()
  }
}

fun View.toggleVisibility(show: Boolean) {
  if (show) {
    this.show()
  } else {
    this.hide()
  }
}

fun View.setBgColor(@ColorRes colorId: Int) {
  val colorInt = ContextCompat.getColor(context, colorId)
  setBackgroundColor(colorInt)
}

fun TextView.setFgColor(@ColorRes colorId: Int) {
  val colorInt = ContextCompat.getColor(context, colorId)
  setTextColor(colorInt)
}

fun TextView.clearDrawable() {
  setCompoundDrawables(null, null, null, null)
}
