package com.ydl.audioim.utils

import android.content.Context
import android.content.Intent
import com.apm.insight.log.VLog
import com.google.gson.Gson
import com.ydl.audioim.http.AudioNetAPi
import com.ydl.consultantim.ConsultantAudioHomeActivity
import com.ydl.ydl_av.chat.bean.AudioMessageBean
import com.ydl.ydlnet.YDLHttpUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

object CallCheck {

    private var subscribe: Disposable? = null

    const val KEY_LATEST_REJECT_CHANNEL = "KeyLatestChannel"

    fun checkCall(context: Context, calleeUid: String? = null, delay: Long = 0) {
        subscribe?.dispose()
        subscribe = Observable.just(1)
            .delay(delay, TimeUnit.SECONDS)
            .flatMap { YDLHttpUtils.obtainApi(AudioNetAPi::class.java).checkCall(calleeUid) }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ resp ->
                if (resp.code == "200" && resp.data != null) {
                    val intent = Intent(context, ConsultantAudioHomeActivity::class.java)
                    val r = resp.data
                    val bean = AudioMessageBean(
                        0, r.channelId, r.userId, r.headImage, r.userName, r.remainingTime, r.callTotalTime,
                        r.relationId, null, null, null
                    )
                    val beanJson = Gson().toJson(bean)
                    intent.putExtra("param", beanJson)
                    context.startActivity(intent)
                    VLog.i("CallCheck", "call check go AudioHomeActivity")
                }
            }, {
                android.util.Log.e("callCheck", it.message)
            })
    }
}