package com.ydl.audioim

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import com.ydl.ydl_av.messge_service.YDLRTMClient
import com.ydl.ydl_av.messge_service.bean.RTMMesssage
import com.ydl.ydl_av.messge_service.callback.InitListener
import com.ydl.ydl_av.messge_service.callback.LoginCallback
import com.ydl.ydl_av.messge_service.request.LoginParam
import com.ydl.audioim.http.AudioApiRequestUtil
import com.ydl.ydlcommon.utils.LogUtil
import com.ydl.ydlcommon.utils.log.LogHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * @author harvie
 * @date 2019/9/27
 * 语音通话入口类
 */
class YDLavManager {


    companion object{
        val instances : YDLavManager by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            YDLavManager()
        }
    }

    private constructor()

    fun init(context: Context,appId:String){
        YDLRTMClient.instances.init(context,appId,listener)
    }

    @SuppressLint("CheckResult")
    fun login(userId:String?){
        if (TextUtils.isEmpty(userId) || userId?:"0" <= "0"){
            //如果uid为空或小于等于0 ，则不进行登录，因为uid为0也会登录成功，会导致后面uid正确时无法登录
            LogUtil.e("[agora]login-uid:$userId")
            return
        }
        //登录实时消息
        //获取token
        AudioApiRequestUtil.getAgoraToken()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if ("200".equals(it.code)){
                        YDLRTMClient.instances.login(LoginParam(userId,it.data.token),object : LoginCallback {
                            override fun onSuccess() {
                                //登陆成功，发起呼叫
                                LogUtil.d("[agora]实时消息登录成功")
                            }

                            override fun onFailure(msg: String?) {
                                LogUtil.d("[agora]实时消息登录失败：$msg")
                            }

                        })
                    }else{
                        LogUtil.e("声网token获取失败uid:"+userId+" error:"+it.msg)
                        LogHelper.getInstance().writeLogSync("声网token获取失败uid:"+userId+" error:"+it.msg)
                    }
                },{
                    LogUtil.e("声网token获取异常uid:"+userId+" error:"+it.message)
                })
    }

    /**
     * 退出登录
     */
    fun logout(){
        YDLRTMClient.instances.logout(object : LoginCallback {
            override fun onSuccess() {
                //退出登陆成功
                LogUtil.d("[agora]实时消息退出成功")
            }

            override fun onFailure(msg: String?) {
                LogUtil.d("[agora]实时消息退出失败：$msg")
            }

        })
    }

    /**
     * 实时消息全局监听
     */
    private val listener = object :InitListener{

        override fun onTokenExpired() {
            LogUtil.e("[agora]onTokenExpired")
        }

        override fun onMessageReceived(message: RTMMesssage, userId: Int) {
            LogUtil.i("[agora]onMessageReceived:${message.text} -->uid:$userId")
        }

        override fun onConnectionStateChanged(state: Int, reason: Int) {
            LogUtil.i("[agora]onConnectionStateChanged:state:${state} -->reason:$reason")
        }

    }
}