package com.musicweb.player.player

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.view.KeyEvent
import androidx.core.content.ContextCompat

class MediaButtonReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action != Intent.ACTION_MEDIA_BUTTON) return
        val event = intent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT) ?: return
        if (event.action != KeyEvent.ACTION_UP) return

        val action = when (event.keyCode) {
            KeyEvent.KEYCODE_MEDIA_PLAY,
            KeyEvent.KEYCODE_MEDIA_PAUSE,
            KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
            KeyEvent.KEYCODE_HEADSETHOOK -> PlayerService.ACTION_TOGGLE
            KeyEvent.KEYCODE_MEDIA_NEXT -> PlayerService.ACTION_NEXT
            KeyEvent.KEYCODE_MEDIA_PREVIOUS -> PlayerService.ACTION_PREVIOUS
            else -> return
        }

        ContextCompat.startForegroundService(
            context,
            Intent(context, PlayerService::class.java).apply { this.action = action }
        )
    }
}
