package ca.ksamad.encore.playback

import android.view.KeyEvent

/**
 * Encapsulates hardware volume-key handling for the foreground Activity.
 *
 * While the app is focused, we want the volume keys to drive the *server* volume **silently** —
 * without the system's volume slider popping up (the app already shows its own). The trick is to
 * fully consume the key event in the Activity so it never reaches the OS volume handling that draws
 * that slider.
 *
 * When the app is backgrounded the Activity isn't in the dispatch path at all, so the
 * `MediaSession`'s `VolumeProvider` handles the keys instead — there the OS remote-volume UI
 * showing up is the expected, cast-style behaviour.
 *
 * Only volume keys we actually act on are consumed: when we're not controlling the server (e.g. the
 * connect screen), the event passes through so the device adjusts its own local volume normally.
 */
class VolumeKeyDispatcher(private val manager: MpdConnectionManager) {
    /**
     * Offer [event] to the volume handler. Returns `true` if it was a volume key we handled and
     * consumed (caller should then *not* pass it on), `false` to let normal dispatch continue.
     */
    fun dispatch(event: KeyEvent): Boolean {
        val up =
            when (event.keyCode) {
                KeyEvent.KEYCODE_VOLUME_UP -> true
                KeyEvent.KEYCODE_VOLUME_DOWN -> false
                else -> return false
            }
        if (!manager.isControllingVolume) return false

        // Nudge on each key-down (auto-repeats included, so holding keeps
        // changing); swallow the key-up too so no system UI flashes.
        if (event.action == KeyEvent.ACTION_DOWN) manager.nudgeVolume(up)
        return true
    }
}
