function property(node, key) {
    const value = node && node.properties ? node.properties[key] : "";
    return typeof value === "string" ? value.trim() : "";
}

function groupKey(node) {
    return property(node, "application.id")
        || property(node, "application.process.binary")
        || property(node, "application.name")
        || `node:${node.id}`;
}

function label(node) {
    return property(node, "application.name")
        || String(node.description || "").trim()
        || property(node, "media.name")
        || "Unknown application";
}

function icon(node) {
    return property(node, "application.icon_name")
        || "audio-x-generic-symbolic";
}

function group(nodes, audioOutStreamFlag) {
    const groups = [];
    const byKey = {};
    for (const node of nodes || []) {
        if (!node || node.ready !== true || !node.audio
                || (node.type & audioOutStreamFlag) !== audioOutStreamFlag)
            continue;
        const key = groupKey(node);
        if (!byKey[key]) {
            byKey[key] = { key, label: label(node), icon: icon(node), nodes: [] };
            groups.push(byKey[key]);
        }
        byKey[key].nodes.push(node);
    }
    return groups;
}

function audioNodes(application) {
    return (application && application.nodes || []).filter(node => node && node.audio);
}

function volume(application) {
    const nodes = audioNodes(application);
    return nodes.length === 0 ? 0
        : nodes.reduce((sum, node) => sum + node.audio.volume, 0) / nodes.length;
}

function muted(application) {
    const nodes = audioNodes(application);
    return nodes.length > 0 && nodes.every(node => node.audio.muted === true);
}

// `max` is the ceiling the value is clamped to, defaulting to 1. It is a
// parameter rather than a constant so over-amplification (1.5) stays a caller's
// decision: this file is deliberately free of any Settings dependency so it can
// be reasoned about -- and tested -- as plain JavaScript.
function setVolume(application, value, max) {
    const requested = Number(value);
    if (!Number.isFinite(requested)) return false;
    const ceiling = Number(max);
    const bound = Number.isFinite(ceiling) && ceiling > 0 ? ceiling : 1;
    const next = Math.max(0, Math.min(bound, requested));
    const nodes = audioNodes(application);
    for (const node of nodes) {
        node.audio.muted = false;
        node.audio.volume = next;
    }
    return nodes.length > 0;
}

function setMuted(application, mutedValue) {
    const nodes = audioNodes(application);
    for (const node of nodes) node.audio.muted = mutedValue === true;
    return nodes.length > 0;
}
