package melody.offline.music.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.offline.Download
import androidx.media3.session.MediaController
import com.bumptech.glide.Glide
import melody.offline.music.R
import melody.offline.music.activity.MoPlayDetailsActivity
import melody.offline.music.activity.PrimaryActivity
import melody.offline.music.ads.AdPlacement
import melody.offline.music.ads.LolAdWrapper
import melody.offline.music.bean.PlaylistItem
import melody.offline.music.fragment.MoHomeFragment
import melody.offline.music.fragment.MoMeFragment
import melody.offline.music.fragment.SearchFragment
import melody.offline.music.media.MediaControllerManager
import melody.offline.music.util.AnalysisUtil

@SuppressLint("ViewConstructor")
class MusicPlayerView(
    val context: Activity,
    val meController: MediaController?,
    val listener :PlaySkipForwardListener,
    attrs: AttributeSet? = null
) :
    LinearLayout(context, attrs) {

    private var goDetailsBtn: LinearLayout
    private var progressBar: CircularProgressBar
    private var playStatusImg: ImageView
    private var audioImg: ImageView
    private var name: TextView
    private var desc: TextView
    private var playBlackBtn: LinearLayout
    private var playSkipForwardBtn:LinearLayout

    init {
        LayoutInflater.from(context).inflate(R.layout.music_player_layout, this, true)
        goDetailsBtn = findViewById(R.id.goDetailsBtn)
        progressBar = findViewById(R.id.progressBar)
        playStatusImg = findViewById(R.id.play_status_img)
        audioImg = findViewById(R.id.audio_img)
        name = findViewById(R.id.name)
        desc = findViewById(R.id.desc)
        playBlackBtn = findViewById(R.id.play_black_btn)
        playSkipForwardBtn = findViewById(R.id.play_skip_forward_btn)
        initOnClickListener()
    }

    private fun initOnClickListener() {
        playBlackBtn.setOnClickListener {
            if (meController != null) {
                if (meController.isPlaying) {
                    meController.pause()
                    updatePlayState(false)
                } else {
                    meController.play()
                    updatePlayState(true)
                }
                updateProgressState(meController)
            }
        }
        playSkipForwardBtn.setOnClickListener {
            if (meController != null) {
                meController.seekToNextMediaItem()
                updateInfoUi(meController.currentMediaItem)
                updateProgressState(meController)
                if (!meController.isPlaying) {
                    meController.prepare()
                    meController.play()
                }

                listener.onOnPlaySkipForwardListener()
            }
        }
        goDetailsBtn.setOnClickListener {
            val intent = Intent(context, MoPlayDetailsActivity::class.java)
            intent.putExtra(
                MoPlayDetailsActivity.PLAY_DETAILS_COME_FROM,
                PrimaryActivity::class.java
            )
            context.startActivity(intent)
        }
    }

    fun updateProgressState(meController: MediaController) {
        //判断是否ready与播放中，否则停止更新进度
        if (meController.playbackState == Player.STATE_READY && meController.isPlaying) {
            updatePlayState(meController.isPlaying)
            progressHandler.removeCallbacksAndMessages(null)
            progressHandler.sendEmptyMessage(1)
        } else {
            progressHandler.removeCallbacksAndMessages(null)
        }
    }

    /**
     * 播放进度
     */
    private val progressHandler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            //判断是否ready与播放中，否则停止更新进度
            if (meController != null && meController.playbackState == Player.STATE_READY && meController.isPlaying) {
                val currentPosition = meController.currentPosition
                progressBar.setProgress(currentPosition)
                sendEmptyMessageDelayed(1, 50)
            }
        }
    }

    fun updatePlayState(b: Boolean) {
        if (b) {
            playStatusImg.setImageResource(R.drawable.playing_black_icon)
        } else {
            playStatusImg.setImageResource(R.drawable.play_black_icon)
        }
    }

    fun updateInfoUi(mediaItem: MediaItem?) {
        if (mediaItem == null) {
            return
        }
        Glide.with(context)
            .load(mediaItem.mediaMetadata.artworkUri)
            .into(audioImg)
        name.text = mediaItem.mediaMetadata.title
        desc.text = mediaItem.mediaMetadata.artist
    }

    fun updateSetProgress(meController: MediaController) {
        progressBar.setMaxProgress(MediaControllerManager.getDuration())
        val currentPosition = meController.currentPosition
        progressBar.setProgress(currentPosition)
    }


    interface PlaySkipForwardListener {
        fun onOnPlaySkipForwardListener(){}
    }
}