package com.yidianling.course.widget

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.SeekBar
import androidx.annotation.DrawableRes
import androidx.annotation.Nullable
import androidx.annotation.RawRes
import com.bumptech.glide.Glide
import com.ydl.media.audio.AudioPlayer
import com.ydl.media.audio.OnPlayerEventListener
import com.ydl.media.audio.enums.PlayModeEnum
import com.ydl.media.audio.model.Music
import com.ydl.media.view.PlayTypeEnum
import com.ydl.media.view.PlayerFloatHelper
import com.yidianling.common.tools.RxNetTool
import com.yidianling.course.R
import kotlinx.android.synthetic.main.audio_play_view.view.*

/**
 * 音频播放UI
 */
class AudioPlayView(context: Context, attrs: AttributeSet?) :
    FrameLayout(context, attrs), OnPlayerEventListener {

    private var mSeekBarIsTouch = false
    private var mProgress = 0
    var mNonWifiTips = true
    var mListener: ((playPosition: Int) -> Boolean)? = null

    init {
        AudioPlayer.get().addOnPlayEventListener(this)
        View.inflate(context, R.layout.audio_play_view, this)
        iv_bg.setOnClickListener {
            if (AudioPlayer.get().isPlaying)
                AudioPlayer.get().pausePlayer()
            else if (AudioPlayer.get().isPausing)
                AudioPlayer.get().startPlayer()
        }
        iv_rewind.setOnClickListener {
            AudioPlayer.get().seekTo(position = AudioPlayer.get().currentPosition.minus(15000))
        }
        iv_fast_forward.setOnClickListener {
            AudioPlayer.get().seekTo(position = AudioPlayer.get().currentPosition.plus(15000))
        }
        iv_pre.setOnClickListener {
            AudioPlayer.get().prev()
        }
        iv_next.setOnClickListener {
            AudioPlayer.get().next()
        }
        seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    tv_progress.text = getStringTime(progress)
                    mProgress = progress
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                mSeekBarIsTouch = true
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                mSeekBarIsTouch = false
                //拖动seekbar时不进行以下操作
                if (!mSeekBarIsTouch) {
                    AudioPlayer.get().seekTo(-1, mProgress.toLong())
                }
            }

        })
    }

    fun setData(playPosition: Int, playList: ArrayList<Music>, from: Int) {
        if (playList.isEmpty()) return
        AudioPlayer.get().playMode = PlayModeEnum.LIST
        AudioPlayer.get().addPlayList(playList)
        if (isPlaying()) mNonWifiTips = false
        if (RxNetTool.isWifi(context)) {
            loadAudio(from, playPosition, playList)
        } else {
            if (mNonWifiTips) {
                showNonWifiTips {
                    mNonWifiTips = false
                    loadAudio(from, playPosition, playList)
                }
            } else {
                loadAudio(from, playPosition, playList)
            }
        }
    }

    private fun showNonWifiTips(block: () -> Unit) {
        block.invoke()
    }

    private fun loadAudio(from: Int, playPosition: Int, playList: ArrayList<Music>) {
        if (isPlaying() && (from == 1 || from == 2)) {
            if (TextUtils.equals(getCurrentUrl(), playList[playPosition].path)) {
                seekbar.max = AudioPlayer.get().getDuration().toInt()
                tv_duration.text = getStringTime(seekbar.max)
                displayPlayStatus(R.drawable.course_pause)
            } else {
                load(playPosition)
            }
        } else {
            load(playPosition)
        }
    }

    /**
     * 获取当前播放url
     */
    private fun getCurrentUrl(): String {
        return AudioPlayer.get().playMusic?.path.orEmpty()
    }

    fun load(index: Int) {
        PlayerFloatHelper.playingType = PlayTypeEnum.PLAY_TYPE_COURSE
        AudioPlayer.get().load(index)
    }

    override fun onPreLoad(playPosition: Int): Boolean {
        return mListener?.invoke(playPosition) ?: true
    }

    @SuppressLint("SetTextI18n")
    override fun onLoad(music: Music) {
        displayPlayStatus(R.drawable.course_loading5, true)
        seekbar.progress = 0
        tv_progress.text = "00:00"
    }

    override fun onStartPlay() {
        postDelayed({
            displayPlayStatus(R.drawable.course_pause)
        }, 200) // 为了列表切换结束后还能看到loading效果
    }

    override fun onPrepared(duration: Long) {
        seekbar.max = duration.toInt()
        tv_duration.text = getStringTime(seekbar.max)
    }

    override fun onBufferingUpdate(percent: Int) {
        seekbar.secondaryProgress = percent * seekbar.max / 100
    }

    override fun onPublish(percent: Int, currentPosition: Long) {
        if (!mSeekBarIsTouch) {
            val currentProgress = currentPosition.toInt()
            seekbar.progress =
                if (seekbar.max - currentProgress < 1000) seekbar.max else currentProgress
            tv_progress.text = getStringTime(seekbar.progress)
        }
    }

    override fun onComplete() {
        tv_progress.text = getStringTime(seekbar.max)
    }

    override fun onPausePlay() {
        displayPlayStatus(R.drawable.course_play)
    }

    private fun displayPlayStatus(
        @RawRes @DrawableRes @Nullable resourceId: Int,
        isGif: Boolean = false
    ) {
        context?.let {
            if (isGif) {
                Glide.with(it).asGif().load(resourceId).into(iv_play_status)
            } else {
                Glide.with(it).asBitmap().load(resourceId).into(iv_play_status)
            }
        }
    }

    private fun getStringTime(time: Int): String {
        if (time <= 0) return "00:00"
        val min = time / 60000
        val ss = (time - min * 60000) / 1000

        var m = "" + min
        var s = "" + ss
        if (min < 10) {
            m = "0$m"
        }
        if (ss < 10) {
            s = "0$ss"
        }
        return "$m:$s"
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        AudioPlayer.get().removeOnPlayEventListener(this)
    }

    fun setSpeed(speed: Float) = AudioPlayer.get().setSpeed(speed)

    fun getSpeed() = AudioPlayer.get().getSpeed()

    fun isPlaying() = AudioPlayer.get().isPlaying

    fun pausePlay() = AudioPlayer.get().pausePlayer()

    fun getAudioMusic() = AudioPlayer.get().playMusic

}