package com.adealink.weparty.profile.dynamic.fragment.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.adealink.frame.log.Log
import com.adealink.weparty.util.formatMissTime

@SuppressLint("UnsafeOptInUsageError")
class VideoTimer @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private var videoDuration: (() -> Long)? = null
    private var videoProgress: (() -> Long)? = null

    private var isPlaying: (() -> Boolean)? = null

    // 更新进度条
    private val updateProgressRunnable = object : Runnable {
        override fun run() {
            val isPlaying = isPlaying?.invoke() ?: false
            val videoProgress = videoProgress?.invoke() ?: 0
            Log.d(TAG, "updateVideoProgress, isPlaying:$isPlaying, progress: $videoProgress")
            if (isPlaying) {
                text = formatMissTime((videoProgress / 1000).toInt())
                postDelayed(this, 300)
            }
        }
    }


    fun setDuration(duration: Long) {
        Log.d(TAG, "setDuration, $duration")
        text = formatMissTime((duration / 1000).toInt())
    }

    fun startTimer(
        videoDuration: () -> Long,
        videoProgress: () -> Long,
        isPlaying: () -> Boolean,
    ) {
        this.videoDuration = videoDuration
        this.videoProgress = videoProgress
        this.isPlaying = isPlaying
        removeCallbacks(updateProgressRunnable)
        post(updateProgressRunnable)
    }

    fun reset() {
        removeCallbacks(updateProgressRunnable)
    }

    companion object {
        const val TAG = "VideoTimer"
    }
}