package com.ydl.audioim.modular

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.ydl.audioim.BuildConfig
import com.ydl.audioim.NetQuality
import com.ydl.audioim.YDLavManager
import com.ydl.audioim.api.IAudioImService
import com.ydl.audioim.http.AudioApiRequestUtil
import com.ydl.audioim.http.REPORT_LEVEL_INFO
import com.ydl.audioim.utils.CallCheck
import com.ydl.audioim.widget.AxbConfirmDialog
import com.ydl.ydl_av.voice.listener.RtcGlobalNet
import com.ydl.ydl_av.voice.manager.YDLVoiceManager
import com.ydl.ydlcommon.modular.findRouteService
import com.ydl.ydlcommon.utils.log.XLog
import com.yidianling.im.api.service.IImService
import io.reactivex.schedulers.Schedulers

/**
 * Created by Ykai on 2022/7/26.
 */

@Route(path = "/audioim/AudioImService")
class AudioImServiceImp : IAudioImService {

    override fun yDLAvManagerInit(context: Context, appId: String) {
        YDLavManager.instances.init(context, appId)
    }


    override fun getIsOnlineRtm(): Boolean {
        return YDLavManager.isOnlineRtm
    }

    override fun loginRtm(userId: String?, event: (isSuccess: Boolean, msg: String?) -> Unit) {
        YDLavManager.instances.login(userId, event)
    }

    override fun loginRtm(userId: String?) {
        YDLavManager.instances.login(userId)
    }

    override fun openAxbDialog(activity: Activity?, type: Int, phoneNumber: String?) {
        val dialog = AxbConfirmDialog(activity, type, object : AxbConfirmDialog.OnClickEnsureListener {
                override fun onClickEnsure() {
                    phoneNumber?.let {
                        val phoneIntent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phoneNumber"))
                        activity?.startActivity(phoneIntent)
                    }
                }

                override fun onClose() {

                }
        })
        dialog.show()
    }

    override fun openPermissionRejectDialog(activity: Activity?, callback: () -> Unit) {
        val dialog = AxbConfirmDialog(activity, 3, object : AxbConfirmDialog.OnClickEnsureListener {
            override fun onClickEnsure() {
                callback.invoke()
            }

            override fun onClose() {
                callback.invoke()
            }
        })
        dialog.show()
    }

    override fun callEventSave(status: String, res: String, session: String?, line: String) {
        YDLavManager.instances.callEventSave(status, res, session, line)
    }

    override fun initRtcNetQuality() {
        YDLVoiceManager.enableLastmileTest(true)
        YDLVoiceManager.attachGlobalNetListener(RtcGlobalNetQuality(30))
    }

    override fun initAgoraRtc(context: Context) {
        YDLVoiceManager.init(context.applicationContext, BuildConfig.AGORA_APPID)
        findRouteService(IImService::class.java).getSystemConfig("network_quality_config")
    }

    override fun reportCallEvent(type: String, name: String, desc: String, retCode: Int?) {
        val resp = hashMapOf<String, Any>(
            "name" to name,
            "desc" to desc,
            "reportLevel" to REPORT_LEVEL_INFO
        )
        if (retCode != null) {
            resp["retCode"] = retCode
        }
        val toJson = Gson().toJson(resp)
        if (YDLVoiceManager.currentChannel.isNullOrEmpty()) return
        AudioApiRequestUtil.callEventSave(YDLVoiceManager.currentChannel, "7", "20", toJson, eventType = type)
            .subscribeOn(Schedulers.io())
            .subscribe()
    }

    override fun callCheck(context: Context, calleeUid: String?, delay: Long) {
        CallCheck.checkCall(context, calleeUid, delay)
    }

    override fun init(context: Context?) {
        NetQuality.copySoundFile(context)
    }
}

internal class RtcGlobalNetQuality(private val threshold: Int) : RtcGlobalNet {
    private var count = 0
    override fun onLastmileQuality(quality: Int) {
        if (quality in 4..6) {
            count++
            if (quality > 3 && count % 10 == 0) {
                XLog.i("RtcGlobalNetQuality", quality.toString())
            }
        }
    }
}