package com.ydl.media.audio

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
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()
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            var nm =  getSystemService(NOTIFICATION_SERVICE) as NotificationManager;
            //数字是随便写的“40”,
            nm.createNotificationChannel( NotificationChannel("40", "App Service", NotificationManager.IMPORTANCE_DEFAULT));
            var builder =  NotificationCompat.Builder(this, "40");

            //其中的2,是也随便写的,正式项目也是随便写
            startForeground(2 ,builder.build());
        }
        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

            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.startForegroundService(intent)
                }else{
                    context.startService(intent)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}