package com.ydl.audioim.player

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.MediaPlayer


/**
 * @author jiucheng
 * @描述:音频播放
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/11/9
 */
class AudioPlayer {
    private var mPlayer: MediaPlayer? = null
    private var mContext: Context? = null
    private var audioManager: AudioManager? = null

    constructor(mContext: Context?, isSpeakerphoneOn: Boolean = false) {
        this.mContext = mContext
        mPlayer = MediaPlayer()
        if (isSpeakerphoneOn) {
            var attributes = AudioAttributes.Builder()
                .setLegacyStreamType(AudioManager.STREAM_MUSIC)
                .build()
            mPlayer?.setAudioAttributes(attributes)

            audioManager = mContext!!.getSystemService(Context.AUDIO_SERVICE) as AudioManager?
            audioManager?.setStreamVolume(
                AudioManager.STREAM_MUSIC,
                audioManager!!.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
                AudioManager.FLAG_PLAY_SOUND
            )
        } else {
            mPlayer?.setAudioStreamType(AudioManager.STREAM_VOICE_CALL)

            var attributes = AudioAttributes.Builder()
                .setLegacyStreamType(AudioManager.STREAM_VOICE_CALL)
                .build()
            mPlayer?.setAudioAttributes(attributes)

            audioManager = mContext!!.getSystemService(Context.AUDIO_SERVICE) as AudioManager?
            audioManager?.setStreamVolume(
                AudioManager.STREAM_VOICE_CALL,
                audioManager!!.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL) / 2,
                AudioManager.STREAM_VOICE_CALL
            )
        }

        audioManager?.isSpeakerphoneOn = isSpeakerphoneOn
    }


    /**
     * 设置音频文件
     * @param id  文件id
     */
    fun setDataSource(id: Int) {
        val file = mContext?.resources?.openRawResourceFd(id)
        if (null == file) {
            return
        }
        if (mPlayer != null) {
            mPlayer?.reset()
            mPlayer?.setDataSource(file.fileDescriptor, file.startOffset, file.length)
        }
        file.close()
    }

    /**
     * 设置两个音乐文件，第一个播放一次，第二个循环播放
     */
    fun setTwoDataAndStart(startMusicId: Int, loopMusicId: Int) {
        requestFocus()
        setDataSource(startMusicId)
        mPlayer?.setOnPreparedListener {
            it.start()
        }
        mPlayer?.setOnCompletionListener {
            it.pause()
            startNext(loopMusicId)
        }
        mPlayer?.prepare()
    }

    /**
     * 播放下一首
     */
    private fun startNext(loopMusicId: Int) {
        setDataSource(loopMusicId)
        start(true, false)
    }


    /**
     * 播放
     * @param isLooping 是否重复播放
     * @param isSetOnCompletionListener 是否设置过播放完成监听
     */
    fun start(isLooping: Boolean, isSetOnCompletionListener: Boolean) {
        requestFocus()
        mPlayer?.isLooping = isLooping
        mPlayer?.setOnPreparedListener {
            it.start()
        }
        if (!isLooping && !isSetOnCompletionListener) {
            mPlayer?.setOnCompletionListener {
                it.pause()
            }
        }
        mPlayer?.prepare()
    }

    /**
     * 设置播放完成回调
     */
    fun setCompletionListener(listener: MediaPlayer.OnCompletionListener) {
        if (listener == null) {
            return
        }
        mPlayer?.setOnCompletionListener(listener)
    }


    /**
     * 切换扬声器、听筒播放方式
     * @param isSpeakerphoneOn  true 扬声器  false 听筒模式
     */
    fun switchPlayType(isSpeakerphoneOn: Boolean) {
        audioManager?.isSpeakerphoneOn = isSpeakerphoneOn
        audioManager?.mode = AudioManager.MODE_IN_CALL
    }

    /**
     * 暂停
     */
    fun pause() {
        if (mPlayer != null) {
            mPlayer?.pause()
        }
    }

    /**
     * 停止
     */
    fun stop() {
        if (mPlayer != null) {
            mPlayer?.stop()
        }
    }

    /**
     * 获取焦点
     *
     */
    fun requestFocus() {
        try {
            val result = audioManager?.requestAudioFocus(
                afChangeListener,
                // Use the music stream.
                AudioManager.STREAM_VOICE_CALL,
                // Request permanent focus.
                AudioManager.AUDIOFOCUS_GAIN
            )
        } catch (e: Exception) {

        }
    }

    fun clear() {
        if (audioManager != null) {
            audioManager?.abandonAudioFocus(afChangeListener)
        }
        if (mPlayer != null) {
            mPlayer?.stop()
            mPlayer?.release()
            mPlayer = null
        }
    }


    var afChangeListener = AudioManager.OnAudioFocusChangeListener {
        if (it == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
            // Pause playback
//            pause()
        } else if (it == AudioManager.AUDIOFOCUS_GAIN) {
            // Resume playback

        } else if (it == AudioManager.AUDIOFOCUS_LOSS) {
            // mAm.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
//            audioManager!!.abandonAudioFocus(afChangeListener)
//            // Stop playback
//            stop()
        }
    }
}
