package com.adealink.weparty.call.comp

import androidx.lifecycle.LifecycleOwner
import com.adealink.weparty.commonui.BaseViewComponent
import io.trtc.tuikit.atomicxcore.api.call.CallParticipantInfo
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

abstract class BaseCallViewComponent(
    lifecycleOwner: LifecycleOwner
) : BaseViewComponent(lifecycleOwner) {

    private var subscribeStateJob: Job? = null

    var callStatus = CallParticipantStatus.None

    override fun observeViewModel() {
        super.observeViewModel()
        subscribeStateJob = CoroutineScope(Dispatchers.Main).launch {
            observeCallState(this)

            CallStore.shared.observerState.selfInfo.collect { selfInfo ->
                onSelfInfoChanged(selfInfo)

                if (callStatus != selfInfo.status && selfInfo.status == CallParticipantStatus.Accept) {
                    callStatus = selfInfo.status
                    onSelfCallStatusChanged(callStatus)
                }
            }

        }
    }

    open fun onSelfInfoChanged(selfInfo: CallParticipantInfo) {

    }

    open fun onSelfCallStatusChanged(status: CallParticipantStatus) {

    }

    open suspend fun observeCallState(scope: CoroutineScope) {}

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

}