package com.yidianling.ydlcommon.custom.player

import android.content.ComponentName
import android.content.ServiceConnection
import android.os.IBinder
import android.text.TextUtils
import com.yidianling.ydlcommon.core.base.BaseApplication
import com.yidianling.ydlcommon.custom.player.player.PlayStatusListener
import com.yidianling.ydlcommon.custom.player.service.HMusicPlayService
import com.yidianling.ydlcommon.custom.utils.AppUtils
import java.util.concurrent.CopyOnWriteArraySet

class YDLMusicPlayer {
    companion object {
        fun getInstance(): YDLMusicPlayer {
            return Holder.INSTANCE
        }
    }

    private object Holder {
        val INSTANCE = YDLMusicPlayer()
    }

    //记录服务是否bind成功，在unbind的时候进行判定，不然未bind成功却进行unbind操作会包错
    private var isConnected = false

    //常用自定义播放状态监听器
    private var listeners: CopyOnWriteArraySet<PlayStateChangeListener> = CopyOnWriteArraySet()
    //完整播放状态监听器
    private var originalListeners: CopyOnWriteArraySet<PlayStatusListener> = CopyOnWriteArraySet()

    //临时播放信息 - 服务未初始化时使用，初始化完成直接播放
    var tempMusicInfoBean: MusicInfoBean? = null
    var tempMusicList: ArrayList<MusicInfoBean>? = null

    //当前播放音乐信息
    var currentMusicInfoBean: MusicInfoBean? = null
    //音乐列表
    var musicList = ArrayList<MusicInfoBean>()
    //播放控制器
    var musicServiceControl: HMusicPlayService.MusicController? = null
    //播放控制器获取回调
    var controlTaker: MusicControlTaker? = null
    //是否自动保存播放进度
    var autoSaveProgress: Boolean = false

    private var musicServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(componentName: ComponentName?, binder: IBinder?) {
            musicServiceControl = binder as HMusicPlayService.MusicController
            controlTaker?.onReceiveControl(musicServiceControl!!)

            play(tempMusicInfoBean, autoSaveProgress)
            play(tempMusicList, autoSaveProgress)

            controlTaker = null
        }

        override fun onServiceDisconnected(p0: ComponentName?) {
        }
    }

    fun addListener(listener: PlayStateChangeListener) {
        listeners.add(listener)
    }

    fun removeListener(listener: PlayStateChangeListener) {
        listeners.remove(listener)
    }

    fun addListener(listener: PlayStatusListener) {
        originalListeners.add(listener)
    }

    fun removeListener(listener: PlayStatusListener) {
        originalListeners.remove(listener)
    }

    fun isPlaying(): Boolean {
        return musicServiceControl?.isPlaying() ?: false
    }

    fun pause() {
        musicServiceControl?.pause();
    }

    fun play(url: String?, autoSaveProgress: Boolean = false) {
        if (TextUtils.isEmpty(url)) {
            return
        }
        play(MusicInfoBean(url), autoSaveProgress)
    }

    fun play(url: String, title: String, cover: String, desc: String, autoSaveProgress: Boolean = false) {
        play(MusicInfoBean(url, title, cover, desc), autoSaveProgress)
    }

    fun play(musicInfoBean: MusicInfoBean?, autoSaveProgress: Boolean = false) {
        if (musicInfoBean == null) {
            return
        }
        if (isPrepareComplete(musicInfoBean, null, autoSaveProgress)) {
            //如果单音频播放与上次播放内容不同则重新设置
//            if (currentMusicInfoBean==null||
//                    musicInfoBean.url != currentMusicInfoBean?.url){
            musicList.clear()
            musicList.add(musicInfoBean)
            currentMusicInfoBean = musicInfoBean
            setData()
//            }
            play(autoSaveProgress)
        }
    }

    fun play(musicInfoList: ArrayList<MusicInfoBean>?, autoSaveProgress: Boolean = false) {
        if (musicInfoList == null || musicInfoList.isEmpty()) {
            return
        }
        if (isPrepareComplete(null, musicInfoList, autoSaveProgress)) {
            //如果不是完全相同则重新设置数据
//            if (!(musicList.containsAll(musicInfoList) && musicInfoList.containsAll(musicList))){
            musicList.clear()
            musicList.addAll(musicInfoList)
            setData()
//            }
            play(autoSaveProgress)
        }
    }

    fun setData() {
        musicServiceControl?.setData(musicList)
        if (tempMusicInfoBean == null && tempMusicInfoBean == null) {
            //非首次设置数据
            for (listener in listeners) {
                //数据重新设置回调
                listener.reset()
            }
        }

        tempMusicInfoBean = null
        tempMusicList = null

        autoSaveProgress = false
    }

    fun play(autoSaveProgress: Boolean = false, index: Int = 0) {
        if (musicServiceControl?.playStatusListener != musicPlayListener) {
            //设置播放监听
            musicServiceControl?.playStatusListener = musicPlayListener
        }
        musicServiceControl?.play(index = index, autoSaveProgress = autoSaveProgress)
    }

    fun start() {
        musicServiceControl?.start()
    }

    /**
     * 播放服务是否初始化完毕
     */
    private fun isPrepareComplete(musicInfoBean: MusicInfoBean?,
                                  musicInfoList: ArrayList<MusicInfoBean>?,
                                  autoSaveProgress: Boolean = false
    ): Boolean {
        if (musicServiceControl == null
                && !AppUtils.isServiceRunning(BaseApplication.getApp(), HMusicPlayService::class.java.name)) {
            tempMusicInfoBean = musicInfoBean
            tempMusicList = musicInfoList
            this.autoSaveProgress = autoSaveProgress
            if (!isConnected) {
                isConnected = MusicPlayerHelper.bindService(
                    BaseApplication.getApp(),
                    musicServiceConnection
                )
            }
            return false
        } else {
            return true
        }
    }

    /**
     * 跳转至
     */
    fun seekTo(position: Int) {
        musicServiceControl?.seekTo(position)
    }

    /**
     * 重新播放
     */
    fun replay() {
        musicServiceControl?.seekTo(0)
        musicServiceControl?.play()
    }

    /**
     * 停止播放
     */
    fun stop() {
        musicServiceControl?.stop()
    }

    /**
     * 销毁服务、移除监听器并释放内存
     */
    fun release() {
        musicServiceControl?.stop()
        listeners.clear()
        originalListeners.clear()
        //销毁后台服务
        if (isConnected) {
            MusicPlayerHelper.unBinderService(
                BaseApplication.getApp(),
                musicServiceConnection
            )
            isConnected = false
        }
        MusicPlayerHelper.stopService(BaseApplication.getApp())
    }

    private var musicPlayListener: PlayStatusListener = object :
        PlayStatusListener {
        override fun beforeStart(index: Int) {
            for (listener in originalListeners) {
                listener.beforeStart(index)
            }
        }

        override fun onPrepared() {
            for (listener in listeners) {
                listener.prepared()
            }

            for (listener in originalListeners) {
                listener.onPrepared()
            }
        }

        override fun start() {
            for (listener in originalListeners) {
                listener.start()
            }
        }

        override fun pause() {
            for (listener in originalListeners) {
                listener.pause()
            }
        }

        override fun loading() {
            for (listener in originalListeners) {
                listener.loading()
            }
        }

        override fun onProgressUpdate(progress: Int) {
            for (listener in originalListeners) {
                listener.onProgressUpdate(progress)
            }
            for (listener in listeners) {
                listener.update(progress, musicServiceControl?.getDuration()!!)
            }
        }

        override fun OnErrorListener(p1: Int, p2: String) {
            for (listener in originalListeners) {
                listener.OnErrorListener(p1, p2)
            }
        }

        override fun OnBufferingUpdateListener(p1: Int) {
            for (listener in originalListeners) {
                listener.OnBufferingUpdateListener(p1)
            }
        }

        override fun onCompletionListener() {
            for (listener in originalListeners) {
                listener.onCompletionListener()
            }

            for (listener in listeners) {
                listener.completion()
            }
        }
    }


    /**
     * 设置播放器控制器回调
     * <课程播放 - HPlayView> 中使用
     */
    fun setMusicControlTaker(taker: MusicControlTaker) {
        if (isPrepareComplete(null, null)) {
            taker.onReceiveControl(musicServiceControl!!)
        } else {
            this.controlTaker = taker;
        }
    }

    interface MusicControlTaker {
        fun onReceiveControl(control: HMusicPlayService.MusicController)
    }

    /**
     * 自定义播放状态监听器
     */
    interface PlayStateChangeListener {

        fun update(time: Int, allTime: Int)

        /**
         * 重新设置数据回调
         * 只有当和上次设置的数据源不同时才会调用
         *
         * 「场景：Page1点击音频播放，显示开始播放状态。
         *        打开Page2开始播放新音频后，Page1应在会回调中重置播放状态」
         */
        fun reset()

        fun completion()

        fun prepared()

    }
}

