//! Default-sink volume and mute, via `pactl`.

use crate::services::process;

/// Current sink volume percentage and mute state. Missing data falls back to
/// 50% / unmuted so the UI stays sane when `pactl` is unavailable.
pub fn read_volume() -> (u8, bool) {
    let percent = process::output("pactl", &["get-sink-volume", "@DEFAULT_SINK@"])
        .and_then(|s| {
            s.split('%')
                .next()
                .and_then(|p| p.split_whitespace().last())
                .and_then(|v| v.parse::<u8>().ok())
        })
        .unwrap_or(50);

    let muted = process::output("pactl", &["get-sink-mute", "@DEFAULT_SINK@"])
        .map(|s| s.contains("yes"))
        .unwrap_or(false);

    (percent, muted)
}

pub fn adjust_volume(up: bool) -> (u8, bool) {
    let step = if up { "+5%" } else { "-5%" };
    let _ = process::run("pactl", &["set-sink-volume", "@DEFAULT_SINK@", step]);
    read_volume()
}

pub fn toggle_mute() -> (u8, bool) {
    let _ = process::run("pactl", &["set-sink-mute", "@DEFAULT_SINK@", "toggle"]);
    read_volume()
}
