package com.tencent.qcloud.tuikit.tuicallkit.manager.bridge

import android.app.Activity
import android.content.Context
import com.adealink.frame.log.Log
import com.adealink.frame.router.Router
import com.adealink.frame.util.ActivityLifecycleCallbacksExt
import com.adealink.frame.util.AppUtil
import com.adealink.weparty.call.constant.TAG_CALL
import com.adealink.weparty.call.constant.TAG_CALL_FLOW
import com.adealink.weparty.module.call.Call
import com.tencent.qcloud.tuicore.TUIConstants
import com.tencent.qcloud.tuicore.TUICore
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuikit.tuicallkit.TUICallKitImpl
import com.tencent.qcloud.tuikit.tuicallkit.manager.CallManager

/**
 * `TUICallKit` uses `ContentProvider` to be registered with `TUICore`.
 * (`TUICore` is the connection and communication class of each component)
 */
class CallServiceInitializer private constructor(context: Context) : ActivityLifecycleCallbacksExt {

    companion object {
        private var instance: CallServiceInitializer? = null
        fun createInstance(context: Context): CallServiceInitializer {
            if (null == instance) {
                synchronized(CallServiceInitializer::class.java) {
                    if (null == instance) {
                        instance = CallServiceInitializer(context)
                    }
                }
            }
            return instance!!
        }
    }

    init {
        val callingService: CallKitService = CallKitService.sharedInstance(context)
        TUICore.registerService(TUIConstants.TUICalling.SERVICE_NAME, callingService)

        val audioRecordService = TUIAudioMessageRecordService(context)
        TUICore.registerService(
            TUIConstants.TUICalling.SERVICE_NAME_AUDIO_RECORD,
            audioRecordService
        )
        TUICallKitImpl.createInstance(context)

        AppUtil.registerActivityLifecycleCallbacks(this)
    }


    override fun onActivityResumed(activity: Activity) {
        super.onActivityResumed(activity)
        handleOfflineCall(activity)
        handleCallingFloatView(activity)
        handleForegroundService(activity)
    }

    /**
     * 处理后台离线消息
     */
    private fun handleOfflineCall(activity: Activity) {
        Log.d(TAG_CALL_FLOW, "handleOfflineCall(onActivityResumed:${activity})")
        val activityCount = AppUtil.getCurrentActivityCount()
        if (activityCount >= 1) {
            //只打开了一个Activity,即首页
            if (TUILogin.isUserLogined()) {
                TUICallKitImpl.createInstance(AppUtil.appContext).queryOfflineCall()
            }
        }
    }

    /**
     * 处理通话中(等待接听,接听中)悬浮窗f
     */
    private fun handleCallingFloatView(activity: Activity) {
        Log.d(TAG_CALL_FLOW, "handleCallingFloatView(onActivityResumed:${activity})")
        if (isMiPushActivity(activity)) {
            return
        }
        val callActivity = Router.getClazz(Call.Call.PATH)?.name
        if (!callActivity.isNullOrEmpty() && callActivity == activity::class.java.name) {
            CallManager.instance.dismissCallingFloatWindow()
        } else {
            CallManager.instance.showCallingFloatWindow { }
        }
    }

    private fun isMiPushActivity(activity: Activity): Boolean {
        try {
            val clazzName = activity.componentName.className
            return clazzName.contains("mipush.sdk")
        } catch (e: Exception) {
            Log.e(TAG_CALL, "isMiPushActivity, ${e.message}", e)
        }
        return false
    }

    private fun handleForegroundService(activity: Activity) {
        Log.d(TAG_CALL_FLOW, "handleForegroundService(onActivityResumed:${activity})")
        CallManager.instance.startForegroundService()
    }
}