package com.yidianling.course.widget

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Handler
import android.view.View
import android.widget.RelativeLayout
import android.widget.SeekBar
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.course.R
import com.yidianling.course.listener.HPlayStatusListener
import kotlinx.android.synthetic.main.course_play_music_view.view.*

/**
 * Created by hgw on 2018/4/28.
 */
class HPlayView : RelativeLayout, OnPlayerEventListener {
    var mHandler: Handler? = null
    var listener: HPlayStatusListener? = null
    //seekBar 按下标记
    var seekBarIsDown = false
    var progress = 0
    var mContext: Activity? = null

    constructor(context1: Activity?) : super(context1) {
        this.mContext = context1
        mHandler = Handler()
        init()
    }


    fun init() {
        if (mContext == null) return
        View.inflate(context, R.layout.course_play_music_view, this)
        AudioPlayer.get().addOnPlayEventListener(this)

        course_audio_play_icon.setOnClickListener {
            AudioPlayer.get().playPause()
        }
        img_gif.setOnClickListener {
            if (!AudioPlayer.get().isPlaying) {
                AudioPlayer.get().playPause()
            }
        }

        pro_progress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                if (p2) {
                    text_start_time.text = getStringTime(p1)
                    progress = p1
                }
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {
                seekBarIsDown = true
            }

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


    fun showNetNotice(event: () -> Unit) {
        ll_net_notice.visibility = View.VISIBLE
        img_gif.visibility = View.GONE
        iv_net_notice.setOnClickListener {
            hideNetNotice()
            event()
        }
    }

    fun hideNetNotice() {
        ll_net_notice.visibility = View.GONE
        img_gif.visibility = View.VISIBLE
    }

    fun setData(urlLi: ArrayList<Music>): HPlayView {
        AudioPlayer.get().addPlayList(urlLi)
        return this
    }

    fun updateView(index: Int) {
        if (AudioPlayer.get().isPlaying) {
            mHandler?.postDelayed({
                pro_progress.max = AudioPlayer.get().getDuration().toInt()
                text_end_time.text = getStringTime(pro_progress.max)
                listener?.onPrepared(AudioPlayer.get().playMusic, index)
            }, 0)
            updateButton()
        }
    }

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

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

    fun setImageBackground(url: String?) {
        Glide.with(mContext).load(url).into(img_bg)
    }

    /**
     * 设置自动播放下一曲
     */
    fun setAutoNext(auto: Boolean) {
        if (!auto) {
            AudioPlayer.get().playMode = PlayModeEnum.SINGLE
        } else {
            AudioPlayer.get().playMode = PlayModeEnum.LIST_LOOP
        }
    }


    @SuppressLint("SetTextI18n")
    override fun onChange(music: Music) {
        if (mContext != null) {
            Glide.with(mContext).asGif().load(R.drawable.course_loading5).into(img_gif)
        }
        course_audio_play_icon.setImageResource(R.drawable.course_ico_course_play)

        pro_progress.progress = 0
        text_start_time.text = "00:00"
    }

    override fun onPlayerStart() {
        setGifVisibity(true)
    }

    override fun onPlayerPause() {
        if (AudioPlayer.get().isPlaying) {
            setGifVisibity(true)
        } else {
            setGifVisibity(false)
        }
    }

    override fun onPublish(percent: Int, currentPosition: Long) {
        if (!seekBarIsDown) {
            pro_progress.progress = currentPosition.toInt()
            text_start_time.text = getStringTime(currentPosition.toInt())
        }
    }

    override fun onBufferingUpdate(percent: Int) {
        showBufferLoading(true)
        mHandler?.postDelayed({
            pro_progress.secondaryProgress = percent * pro_progress.max / 100
        }, 0)
    }

    override fun onPrepared(duration: Long) {
        mHandler?.postDelayed({
            pro_progress.max = duration.toInt()
            text_end_time.text = getStringTime(pro_progress.max)
            var index = AudioPlayer.get().getMusicList()?.indexOf(AudioPlayer.get().playMusic) ?: 0
            listener?.onPrepared(
                AudioPlayer.get().playMusic, index
            )
        }, 0)

    }

    override fun onComplete() {
        updateButton()
    }


    private fun showBufferLoading(show: Boolean) {
        mHandler?.postDelayed({
            if (show) {
                if (!AudioPlayer.get().isPlaying) {
                    if (mContext != null) {
                        Glide.with(mContext).asGif().load(R.drawable.course_loading5).into(img_gif)
                    }
                    course_audio_play_icon.setImageResource(R.drawable.course_ico_course_play)
                }
            } else {
                if (mContext != null) {
                    Glide.with(mContext).asGif().load(R.drawable.course_audio_play).into(img_gif)
                }
                course_audio_play_icon.setImageResource(R.drawable.course_ico_course_pause)
            }
        }, 0)
    }

    //显示或隐藏播放动画
    private fun setGifVisibity(show: Boolean) {
        if (mContext == null) return
        mHandler?.postDelayed({
            if (show) {
                Glide.with(mContext).asGif().load(R.drawable.course_audio_play).into(img_gif)
                course_audio_play_icon.setImageResource(R.drawable.course_ico_course_pause)
            } else {
                Glide.with(mContext).asBitmap().load(R.drawable.course_ico_course_bg_pause)
                    .into(img_gif)
                course_audio_play_icon.setImageResource(R.drawable.course_ico_course_play)
            }
        }, 0)
    }

    //跟新上下音频按钮状态

    private fun updateButton() {
        mHandler?.postDelayed({
            if (AudioPlayer.get().isPlaying) {
                setGifVisibity(true)
            }
        }, 300)

    }

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

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

    fun onDestroy() {
        AudioPlayer.get().removeOnPlayEventListener(this)
        mContext = null
        mHandler = null
    }
}