package com.adealink.weparty.call

import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.os.Build
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.updateLayoutParams
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.router.annotation.RouterUri
import com.adealink.weparty.call.comp.BgComp
import com.adealink.weparty.call.comp.CallBottomComp
import com.adealink.weparty.call.comp.CallOrderComp
import com.adealink.weparty.call.comp.CallTopComp
import com.adealink.weparty.call.comp.CallUserInfoComp
import com.adealink.weparty.call.databinding.ActivityCallBinding
import com.adealink.weparty.call.interceptor.EnterCallUriInterceptor
import com.adealink.weparty.call.util.PermissionRequest
import com.adealink.weparty.commonui.BaseActivity
import com.adealink.weparty.module.call.Call
import com.adealink.weparty.util.QMUIStatusBarHelper
import com.adealink.weparty.util.applyImmersive
import com.tencent.qcloud.tuicore.permission.PermissionCallback
import com.tencent.qcloud.tuikit.tuicallkit.common.data.Constants
import com.tencent.qcloud.tuikit.tuicallkit.common.metrics.KeyMetrics
import com.tencent.qcloud.tuikit.tuicallkit.common.utils.CallUtils.isCaller
import com.tencent.qcloud.tuikit.tuicallkit.common.utils.DeviceUtils
import com.tencent.qcloud.tuikit.tuicallkit.manager.CallManager
import com.tencent.qcloud.tuikit.tuicallkit.state.GlobalState
import com.tencent.qcloud.tuikit.tuicallkit.state.ViewState
import com.trtc.tuikit.common.ui.floatwindow.FloatWindowManager
import io.trtc.tuikit.atomicxcore.api.call.CallMediaType
import io.trtc.tuikit.atomicxcore.api.call.CallParticipantStatus
import io.trtc.tuikit.atomicxcore.api.call.CallStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch


/**
 * 不要直接通过Intent启动CallActivity
 */
@RouterUri(
    path = [Call.Call.PATH],
    interceptors = [EnterCallUriInterceptor::class],
    desc = "1v1 Call"
)
class CallActivity : BaseActivity() {

    private val binding by viewBinding(ActivityCallBinding::inflate)

    private var subscribeStateJob: Job? = null

    @SuppressLint("CommitTransaction")
    override fun initViews() {
        super.initViews()
        QMUIStatusBarHelper.setStatusBarLightMode(this)
        setContentView(binding.root)
        this@CallActivity.applyImmersive { top ->
            binding.idCallTopBar.root.updateLayoutParams<ConstraintLayout.LayoutParams> {
                topMargin = top
            }
        }

        DeviceUtils.setScreenLockParams(window)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true)
            setTurnScreenOn(true)
        }
        requestedOrientation = when (GlobalState.instance.orientation) {
            Constants.Orientation.Portrait -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            Constants.Orientation.LandScape -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
            else -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
        }
        subscribeStateJob = CoroutineScope(Dispatchers.Main).launch {
            observeSelfInfo()
        }
    }

    override fun initComponents() {
        super.initComponents()
        BgComp(this, binding.vBg).attach()
        CallUserInfoComp(this, binding.vUserInfo).attach()
        CallTopComp(this, binding.idCallTopBar) {
            finishCallActivity()
        }.attach()
        CallBottomComp(this, binding.idCallBottomBar).attach()
        CallOrderComp(this, binding.vOrderInfo).attach()
    }

    override fun onResume() {
        super.onResume()
        PermissionRequest.requestPermissions(
            application, CallMediaType.Audio,
            object : PermissionCallback() {
                override fun onGranted() {
                    inflateView()
                }

                override fun onDenied() {
                    val self = CallStore.shared.observerState.selfInfo.value
                    if (!isCaller(self.id)) {
                        CallManager.instance.reject(null)
                    }
                    finishCallActivity()
                }
            })
    }

    private fun inflateView() {
        val callStatus = CallStore.shared.observerState.selfInfo.value.status
        if (CallParticipantStatus.None == callStatus) {
            finishCallActivity()
            return
        }
        val callId = CallStore.shared.observerState.activeCall.value.callId
        KeyMetrics.countUV(KeyMetrics.EventId.WAKEUP, callId)
        FloatWindowManager.sharedInstance().dismiss()
        CallManager.instance.viewState.router.set(ViewState.ViewRouter.FullView)
    }

    private suspend fun observeSelfInfo() {
        CallStore.shared.observerState.selfInfo.collect { selfInfo ->
            if (selfInfo.status == CallParticipantStatus.None) {
                finishCallActivity()
                return@collect
            }
        }
    }

    private fun finishCallActivity() {
        finishAndRemoveTask()
    }

    override fun onDestroy() {
        super.onDestroy()
        subscribeStateJob?.cancel()
    }

}