package com.yidianling.ydlcommon.custom.player.view

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.yidianling.ydlcommon.R
import com.yidianling.ydlcommon.custom.player.MusicInfoBean
import com.yidianling.ydlcommon.custom.player.YDLMusicHelper
import com.yidianling.ydlcommon.custom.player.YDLMusicPlayer
import com.yidianling.ydlcommon.custom.player.player.HPlayStatusListener
import com.yidianling.ydlcommon.custom.player.player.PlayStatusListener
import com.yidianling.ydlcommon.custom.player.service.HMusicPlayService
import kotlinx.android.synthetic.main.play_music_view.view.*

/**
 * Created by hgw on 2018/4/28.
 */
class HPlayView : RelativeLayout, YDLMusicPlayer.MusicControlTaker {
    var control: HMusicPlayService.MusicController? = null
    var listener: HPlayStatusListener? = null

    var mHandler: Handler? = 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
        YDLMusicPlayer.getInstance().setMusicControlTaker(this)

        View.inflate(context, R.layout.play_music_view, this)

        play_icon.setOnClickListener {
            if (control?.isPlaying() == true) {
                control?.pause()
            } else {
                control?.start()
            }
        }
        img_gif.setOnClickListener {
            if (control?.isPlaying() == false) {
                control?.start()
            }
        }

        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) {
                    control?.seekTo(progress)
                }
            }
        })
    }


    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<MusicInfoBean>): HPlayView {
        control?.setData(urlLi)
        return this
    }

    /**
     * 后台进入前台view
     */
    fun updateView(index: Int) {
        if (control?.isPlaying()!!) {
            mHandler?.postDelayed({
                pro_progress.max = control?.getDuration() ?: 0
                text_end_time.text = getStringTime(pro_progress.max)
                listener?.onPrepared(control?.getCurrentData(), index)
            }, 0)
            updateButton()
        }
    }

    /**
     * 获取当前播放下标
     */
    fun getCurrentIndex(): Int {
        return control?.getCurrentIndex() ?: 0
    }

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

    fun play(index: Int) {
        updateButton()
        YDLMusicHelper.playingType = YDLMusicHelper.PLAY_TYPE_COURSE
        YDLMusicHelper.directPlay(index, true)
    }

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

    /**
     * 获取播放控制器
     */
    fun getPlayControl(): HMusicPlayService.MusicController? {
        return control
    }

    /**
     * 设置自动播放下一曲
     */
    fun setAutoNext(auto: Boolean) {
        control?.setAutoPlayNext(auto)
    }

    override fun onReceiveControl(control: HMusicPlayService.MusicController) {
        this.control = control
        setControl1(control)
    }

    var playStatusListener: PlayStatusListener? = null

    private fun setControl1(control: HMusicPlayService.MusicController?) {
        control?.setOpenNotifyCation(true)
        if (playStatusListener == null) {
            playStatusListener = object : PlayStatusListener {
                override fun beforeStart(index: Int) {
                    showBufferLoading(true)
                }

                override fun onCompletionListener() {
//                    LogH.d("onCompletionListener")
                    updateButton()
                }

                override fun loading() {
//                    LogH.d("loading")
                    showBufferLoading(true)
                }

                override fun onPrepared() {
//                    LogH.d("onPrepared")
                    mHandler?.postDelayed({
                        pro_progress.max = control?.getDuration() ?: 0
                        text_end_time.text = getStringTime(pro_progress.max)
                        listener?.onPrepared(control?.getCurrentData(), control?.getCurrentIndex()
                                ?: 0)
                    }, 0)
                }

                override fun start() {
//                    LogH.d("start")
                    setGifVisibity(true)
                }

                override fun pause() {
//                    LogH.d("pause")
                    setGifVisibity(false)
                }

                override fun onProgressUpdate(progress: Int) {
                    mHandler?.postDelayed({
                        //拖动seekbar时不进行以下操作
                        if (!seekBarIsDown) {
                            pro_progress.progress = progress
                            text_start_time.text = getStringTime(progress)
                        }
                    }, 0)
                }

                override fun OnErrorListener(p1: Int, p2: String) {
//                    LogH.d("OnErrorListener:$p1  $p2")
                    setGifVisibity(false)
                }

                override fun OnBufferingUpdateListener(p1: Int) {
//                    LogH.d("OnBufferingUpdateListener:$p1")
                    mHandler?.postDelayed({
                        pro_progress.secondaryProgress = p1 * pro_progress.max / 100
                    }, 0)

                }
            }
            YDLMusicPlayer.getInstance().addListener(playStatusListener!!)
        }
    }

    fun showBufferLoading(show: Boolean) {
        mHandler?.postDelayed({
            if (show) {
                if (mContext != null) {
                    Glide.with(mContext).asGif().load(R.mipmap.loading5).into(img_gif)
                }

                play_icon.setImageResource(R.drawable.ico_course_play)
            } else {
                if (mContext != null) {
                    Glide.with(mContext).asGif().load(R.mipmap.audio_play).into(img_gif)
                }
                play_icon.setImageResource(R.drawable.ico_course_pause)
            }
        }, 0)
    }

    //显示或隐藏播放动画
    fun setGifVisibity(show: Boolean) {
        if (context == null) return
        mHandler?.postDelayed({
            if (show) {
                if (mContext != null) {
                    Glide.with(mContext).asGif().load(R.mipmap.audio_play).into(img_gif)
                }
                play_icon.setImageResource(R.drawable.ico_course_pause)
            } else {
                if (mContext != null) {
                    Glide.with(mContext).asBitmap().load(R.drawable.ico_course_bg_pause).into(img_gif)
                }
                play_icon.setImageResource(R.drawable.ico_course_play)
            }
        }, 0)
    }

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

    fun updateButton() {
        mHandler?.postDelayed({
            if (control?.isPlaying() == true) {
                setGifVisibity(true)
            }
        }, 0)

    }

    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() {
        mContext = null
        mHandler = null
        playStatusListener?.let { YDLMusicPlayer.getInstance().removeListener(it) }
    }
}