package com.base.appzxhy.utils

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

object ClickTimesUtils {

    private val TAG = "ClickTimesUtils"
    private var lastClickTime = 0L
    private var continuousTimes = 0
    private var resetJob: Job? = null

    private fun startResetJob() {
        if (resetJob == null) {
            resetJob = MainScope().launch(Dispatchers.IO) {
                delay(3000)
                lastClickTime = 0L
                continuousTimes = 0
                resetJob = null
                LogEx.logDebug(TAG, "reset job")
            }
        }
    }

    fun isContinuousTimesClick(times: Int = 8): Boolean {

        startResetJob()

        val lastClickInterval = System.currentTimeMillis() - lastClickTime
        val thisContinue = lastClickInterval < 500L || lastClickTime == 0L

        LogEx.logDebug(TAG, "lastClickInterval=$lastClickInterval lastClickTime=$lastClickTime continuousTimes=$continuousTimes")

        if (thisContinue) {
            continuousTimes++
            lastClickTime = System.currentTimeMillis()
            if (continuousTimes >= times) {
                lastClickTime = 0
                continuousTimes = 0
                resetJob?.cancel()
                resetJob = null
                LogEx.logDebug(TAG, "reset times click")
                return true
            }
        }
        return false
    }

}