package com.tencent.qcloud.tuikit.tuicallkit.widget

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.tencent.qcloud.tuicore.util.DateTimeUtil
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 TimerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyle: Int = 0,
) : AppCompatTextView(context, attrs, defStyle) {
    private var subscribeStateJob: Job? = null

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        if (isInEditMode) {
            return
        }
        initView()
        registerActiveCallObserver()
    }

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

    private fun registerActiveCallObserver() {
        subscribeStateJob = CoroutineScope(Dispatchers.Main).launch {
            CallStore.shared.observerState.activeCall.collect { activeCall ->
                updateDurationView(activeCall.duration)
            }
        }
    }

    private fun initView() {
        //setTextColor(ContextCompat.getColor(context, R.color.callview_color_white))
        val duration = CallStore.shared.observerState.activeCall.value.duration
        updateDurationView(duration)
    }

    private fun updateDurationView(time: Long) {
        val self = CallStore.shared.observerState.selfInfo.value
        if (self.status == CallParticipantStatus.Accept) {
            text = DateTimeUtil.formatSecondsTo00(time.toInt())
            visibility = VISIBLE
        } else {
            visibility = GONE
        }
    }
}