package com.waytous.anticollision.concurrent

import com.blankj.utilcode.util.LogUtils
import com.waytous.anticollision.BuildConfig
import com.waytous.anticollision.tcp.Error
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.Lock

class Signal(private val lock: Lock, private val count:Int) {

    private val condition: Condition = lock.newCondition()

    val flag by lazy {
        AtomicReference(Error.NOError)
    }
    val retryCount:AtomicInteger = AtomicInteger(count)

    val mResult by lazy {
        AtomicReference(Result.Timeout)
    }

    enum class Result(val value:Int){
        Invalid(-1),
        Success(0),
        Timeout(1),
        Cancelled(2),
    }

    fun taskWait(time:Long){
        lock.lock()
        try {
            condition.await()
        } catch (e:InterruptedException) {
            if (BuildConfig.DEBUG) {
                LogUtils.e("send data error:${e.message}")
            } else {
                LogUtils.file("send data error:${e.message}")
            }
        }finally {
            lock.unlock()
        }
    }
}