package cn.yyxx.eyuangame.core.utils

import android.os.Looper
import cn.yyxx.eyuangame.base.utils.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch


/**
 * @author #Suyghur.
 * Created on 2020/12/9
 */
object TimeDownUtils {

    var isRunning = false
    private var isCancel = false

    var scope: CoroutineScope = CoroutineScope(Dispatchers.IO + Job())

    @Volatile
    private var times: Times? = null

    fun start(time: Int, callback: TimeCallback) {
        if (isRunning) {
            Logger.e("倒计时还在执行中...")
        } else {
            isRunning = true
            isCancel = false
            times = Times(time, callback)
            times!!.start()
        }
    }


    fun cancel() {
        isCancel = true
        if (isRunning) {
            times?.apply {
                interrupt()
                times = null
            }
        }
        isRunning = false
        Logger.d("TimeDownUtils.cancel")
    }

    fun resetCallback(callback: TimeCallback) {
        times?.apply {
            this.callback = callback
        }
    }

    fun startScope(time: Int, callback: TimeCallback) {
        scope.launch {
            timeScope(time, callback)
        }
    }

    private fun timeScope(time: Int, callback: TimeCallback) {
//        callback.onTime(time)
        Logger.d("timeScope 倒计时开始... , ${Looper.getMainLooper().thread == Thread.currentThread()}")
        for (i in time downTo 0) {
            try {
                Thread.sleep(1000)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
//            if (isCancel) {
//                Logger.d("TimeDownUtils 线程已退出")
//                return
//            }
            callback.onTime(i)
        }
    }

//    fun isRunning(): Boolean {
//        return isRunning
//    }


    interface TimeCallback {
        fun onTime(time: Int)
    }

    private class Times(val time: Int, var callback: TimeCallback) : Thread() {

        override fun run() {
            callback.onTime(time)
            Logger.d("timeDownUtils 倒计时开始...")
            for (i in time downTo 0) {
                try {
                    sleep(1000)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
                if (isCancel) {
                    Logger.d("TimeDownUtils 线程已退出")
                    return
                }
                callback.onTime(i)
            }
            cancel()
        }
    }

}