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

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.media3.common.Player
import com.adealink.weparty.profile.databinding.WidgetDynamicVideoTimeBarBinding

@SuppressLint("UnsafeOptInUsageError")
class VideoSeekBar @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {

    private val binding =
        WidgetDynamicVideoTimeBarBinding.inflate(LayoutInflater.from(context), this)

    init {
        binding.seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
//                seekBar?.progress?.let {
//                    startScrubbing(it.toLong())
//                }
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                player?.let { player ->
                    val duration = player.duration
                    if (duration > 0) {
                        val targetPosition = seekBar?.progress?.toLong() ?: 0
                        player.seekTo(targetPosition)
                    }
                }
            }
        })
    }


    // 更新进度条
    private val updateProgressRunnable = object : Runnable {
        override fun run() {
            val player = player ?: return
            if (player.isPlaying) {
                val duration = player.duration
                val currentPosition = player.currentPosition.toInt()
                if (duration > 0) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        binding.seekBar.setProgress(currentPosition, true)
                    } else {
                        binding.seekBar.progress = currentPosition
                    }
                }
            }
            binding.seekBar.postDelayed(this, 100) // 每秒更新一次
        }
    }

    private var player: Player? = null
    fun bindPlayer(player: Player?) {
        this.player = player
        binding.seekBar.max = player?.duration?.toInt() ?: 100
        binding.seekBar.progress = player?.currentPosition?.toInt() ?: 0
        post(updateProgressRunnable)
    }

    fun release() {
        this.player = null
    }

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