package com.yidianling.muse.helper

import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import kotlin.properties.Delegates

class MediaPlayerManager private constructor() {

    private var listener:OnMediaPlayerManagerListener?=null

    fun setAudioPath(path: String){
        mPath = path
        mMediaPlayer?.reset()
        mMediaPlayer?.setDataSource(mContext, Uri.parse(path))
        mMediaPlayer?.prepareAsync()
        mMediaPlayer?.setOnPreparedListener {
            listener?.onPrepared(it)
        }
    }

    fun getMediaPlayer():MediaPlayer?  = mMediaPlayer

    fun getAudioPath():String? = mPath

    fun isPlaying() = mMediaPlayer?.isPlaying

    fun play() {
        if (mMediaPlayer?.isPlaying == true) return
        mMediaPlayer?.start()
    }

    fun pause() {
        if (mMediaPlayer?.isPlaying == true) mMediaPlayer?.pause()
    }

    fun seekTo(position: Int) {
        mMediaPlayer?.seekTo(position)
    }

    fun stop() {
        if (mMediaPlayer?.isPlaying == true) {
            mMediaPlayer?.reset()
        }
    }

    fun release() {
        mMediaPlayer?.reset()
    }

    fun setOnPreparedListener(listener: OnMediaPlayerManagerListener){
        this.listener = listener
    }

    companion object {

        private var mContext: Context by Delegates.notNull()

        private var mMediaPlayer:MediaPlayer? = null

        private var mPath:String? = null

        @Volatile
        private var instance: MediaPlayerManager? = null

        fun getInstance(context: Context): MediaPlayerManager? {
            return when{
                instance != null -> instance
                else -> synchronized(this) {
                    if (instance == null){
                        mContext = context
                        mMediaPlayer = MediaPlayer()
                        instance = MediaPlayerManager()
                    }
                    instance
                }
            }
        }
    }


    interface OnMediaPlayerManagerListener{
        fun onPrepared(mediaPlayer: MediaPlayer)
    }

}