package com.ydl.media.audio

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import com.ydl.media.audio.constants.Extras
import com.ydl.media.audio.manager.MediaSessionManager
import com.ydl.media.audio.manager.NotifyManager

/**
 * Created by haorui on 2019-10-27 .
 * Des: 音乐播放后台服务
 */
class PlayService : Service() {

    inner class PlayBinder : Binder() {
        val service: PlayService
            get() = this@PlayService
    }

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "onCreate: " + javaClass.simpleName)
        AudioPlayer.get().init(this)
        MediaSessionManager.get().init(this)
        NotifyManager.get().init(this)
    }

    override fun onBind(intent: Intent): IBinder? {
        return PlayBinder()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null && intent.action != null) {
            when (intent.action) {
                Extras.ACTION_STOP -> stop()
            }
        }
        return Service.START_NOT_STICKY
    }

    private fun stop() {
        AudioPlayer.get().stopPlayer()
        NotifyManager.get().cancelAll()
    }

    companion object {
        private val TAG = "Service"

        fun startCommand(context: Context, action: String) {
            val intent = Intent(context, PlayService::class.java)
            intent.action = action
            context.startService(intent)
        }
    }
}