package com.adealink.weparty.call.widget.float.calling

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import com.adealink.weparty.call.R
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
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

/**
 * 通话浮动视图
 */
class CallingView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private var subscribeStateJob: Job? = null
    private var callStatus = CallParticipantStatus.None

    private var hintView: View? = null
    private var timerView: View? = null

    init {
        initView(context)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        registerObserver()
    }

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

    private fun registerObserver() {
        subscribeStateJob = CoroutineScope(Dispatchers.Main).launch {
            launch { observeCallStatus() }
        }
    }

    private suspend fun observeCallStatus() {
        CallStore.shared.observerState.selfInfo.collect { selfInfo ->
            if (callStatus != selfInfo.status) {
                callStatus = selfInfo.status
                onCallStatusChanged()
            }
        }
    }

    private fun initView(context: Context) {
//        val binding = CallFloatCallViewBinding.inflate(LayoutInflater.from(context), this, true)
        LayoutInflater.from(context).inflate(R.layout.call_float_call_view, this)
        hintView = findViewById(R.id.tv_hint)
        timerView = findViewById(R.id.tv_timer)
    }

    private fun onCallStatusChanged() {
        when (callStatus) {
            CallParticipantStatus.None -> {

            }

            CallParticipantStatus.Waiting -> {
                hintView?.show()
                timerView?.gone()
            }

            CallParticipantStatus.Accept -> {
                hintView?.gone()
                timerView?.show()
            }
        }
    }

}