#!/usr/bin/python3
"""plinius-headset: settings of Bluetooth headphones for the device page of GNOME Bluetooth.

A session D-Bus service (org.plinius.Headset) behind Settings › Bluetooth › device. It gives
every setting it knows of one device in one form (id, category, type, label, value, options),
so the device page draws them without knowing where they come from:

- group "audio", for every headphone: the codec (PipeWire's A2DP profiles of the card), the
  battery (BlueZ) and an equalizer on the phone. The equalizer is a PipeWire filter chain per
  device (plinius-eq.service), a smart filter WirePlumber puts in front of that device only;
  its bands change live, switching it on or off restarts the filter host.
- group "vendor": what the headphones themselves can do (noise canceling, their own equalizer,
  LDAC, buttons, …) over the maker's protocol. Soundcore through openscq30; its settings and
  categories carry ids only, their names come from openscq30's translations.

Values: toggle b, select s, range i, equalizer ai (tenths of a dB or the maker's steps, see
fraction-digits), info s, action (no value).
"""

import gettext
import json
import locale
import math
import os
import re
import signal
import subprocess
import sys

import gi

gi.require_version("GLibUnix", "2.0")
from gi.repository import Gio, GLib, GLibUnix  # noqa: E402

_translation = gettext.translation("plinius-headset", fallback=True)
_ = _translation.gettext
ngettext = _translation.ngettext

BUS_NAME = "org.plinius.Headset"
OBJECT_PATH = "/org/plinius/Headset"
IFACE = "org.plinius.Headset1"
ERROR_PREFIX = "org.plinius.Headset.Error."

BLUEZ = "org.bluez"
BLUEZ_DEVICE_IFACE = "org.bluez.Device1"
BLUEZ_BATTERY_IFACE = "org.bluez.Battery1"
AUDIO_SINK_UUID = "0000110b-0000-1000-8000-00805f9b34fb"

# Soundcore's own RFCOMM service: the last five hex digits differ per model
SOUNDCORE_UUID = re.compile(r"^0cf12d31-fac3-4553-bd80-d6832e7[0-9a-f]{5}$")
OPENSCQ30 = "openscq30"
OPENSCQ30_I18N = "/usr/share/openscq30/i18n"
OPENSCQ30_FTL = "openscq30-lib.ftl"
# Our own translations of what openscq30's are still missing, one <lang>.ftl per language
OPENSCQ30_EXTRA = "/usr/share/plinius-headset/openscq30"
# Settings whose message is not their id spelled out (#[translate] in openscq30's settings.rs)
VENDOR_KEYS = {
    "presetEqualizerProfile": "preset-profile",
    "customEqualizerProfile": "custom-profile",
    "limitHighVolumeDbLimit": "db-limit",
    "limitHighVolumeRefreshRate": "db-refresh-rate",
}
# Durations among openscq30's options: 10s, 1m, 60m
VENDOR_DURATION = re.compile(r"^([0-9]+)([smh])$")
# openscq30 setting types the page can show, as the page's type names
VENDOR_TYPES = {
    "toggle": "toggle",
    "i32Range": "range",
    "select": "select",
    "optionalSelect": "select",
    "equalizer": "equalizer",
    "information": "info",
    "action": "action",
}
# A headphone answers in a few seconds; one that does not is out of reach
VENDOR_TIMEOUT = 20

# Bands of the phone's equalizer (Hz), the outer two as shelves
EQ_BANDS = (31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000)
EQ_LIMIT = 120  # ±12 dB in tenths
EQ_Q = 1.41  # about one octave per band
EQ_PRESETS = {
    "flat": (0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
    "bass": (60, 50, 40, 20, 0, 0, 0, 0, 0, 0),
    "treble": (0, 0, 0, 0, 0, 0, 20, 40, 50, 60),
    "voice": (-20, -20, -10, 0, 20, 40, 40, 20, 0, -10),
    "loudness": (50, 40, 20, 0, -10, -10, 0, 20, 40, 50),
    "soft": (0, 0, 0, 0, 0, 0, -10, -20, -30, -40),
}
EQ_UNIT = "plinius-eq.service"
IDLE_EXIT_SECONDS = 300

INTERFACE_XML = f"""
<node>
  <interface name="{IFACE}">
    <method name="GetSettings">
      <arg type="s" name="address" direction="in"/>
      <arg type="s" name="group" direction="in"/>
      <arg type="aa{{sv}}" name="settings" direction="out"/>
    </method>
    <method name="SetSetting">
      <arg type="s" name="address" direction="in"/>
      <arg type="s" name="id" direction="in"/>
      <arg type="v" name="value" direction="in"/>
      <arg type="aa{{sv}}" name="settings" direction="out"/>
    </method>
    <method name="HasVendorSettings">
      <arg type="s" name="address" direction="in"/>
      <arg type="s" name="vendor" direction="out"/>
    </method>
    <signal name="Changed">
      <arg type="s" name="address"/>
      <arg type="s" name="group"/>
    </signal>
  </interface>
</node>
"""


def log(*args):
    print(*args, file=sys.stderr, flush=True)


class HeadsetError(Exception):
    """A failure the caller shows: name is the D-Bus error's last part."""

    def __init__(self, name, message):
        super().__init__(message)
        self.name = name


def valid_address(address):
    return re.fullmatch(r"[0-9A-F]{2}(:[0-9A-F]{2}){5}", address or "") is not None


def device_path(address):
    return "/org/bluez/hci0/dev_" + address.replace(":", "_")


def config_dir():
    return os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"))


def setting(sid, category, category_label, kind, label, value=None, **extra):
    """One setting as the page gets it (a{sv})."""
    d = {
        "id": GLib.Variant("s", sid),
        "category": GLib.Variant("s", category),
        "category-label": GLib.Variant("s", category_label),
        "type": GLib.Variant("s", kind),
        "label": GLib.Variant("s", label),
    }
    if value is not None:
        d["value"] = GLib.Variant("v", value)
    for key, v in extra.items():
        d[key.replace("_", "-")] = v
    return d


# ----- translations of openscq30 -----

def ui_languages():
    """The user's languages, most wanted first, as openscq30's folder names."""
    langs = []
    for var in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"):
        value = os.environ.get(var, "")
        if not value:
            continue
        for part in value.split(":"):
            code = part.split(".")[0].split("@")[0]
            if code and code not in ("C", "POSIX"):
                langs.append(code)
        if var != "LANGUAGE":
            break
    out = []
    for code in langs:
        lang, _sep, region = code.partition("_")
        for name in (f"{lang}-{region}" if region else None, lang,
                     "pt-BR" if lang == "pt" else None):
            if name and name not in out:
                out.append(name)
    out.append("en")
    return out


def parse_ftl(text):
    """The plain messages of a Fluent file (key = value); anything else is skipped."""
    messages = {}
    for line in text.splitlines():
        m = re.match(r"^([a-z0-9][a-z0-9-]*)\s*=\s*(\S.*)$", line)
        if m and "{" not in m.group(2):
            messages[m.group(1)] = m.group(2).strip()
    return messages


def read_ftl(path):
    try:
        with open(path, encoding="utf-8") as f:
            return parse_ftl(f.read())
    except OSError:
        return {}


def ftl_key(ident):
    """ambientSoundMode → ambient-sound-mode"""
    return re.sub(r"(?<=[a-z0-9])([A-Z])", r"-\1", ident).lower()


class VendorNames:
    def __init__(self, root=OPENSCQ30_I18N, languages=None, extra=OPENSCQ30_EXTRA):
        self.messages = {}
        for lang in reversed(languages or ui_languages()):
            # openscq30's own translation wins, ours only fills its gaps
            self.messages.update(read_ftl(os.path.join(extra, lang + ".ftl")))
            self.messages.update(read_ftl(os.path.join(root, lang, OPENSCQ30_FTL)))
        # openscq30's command line labels its options in English only
        self.english = read_ftl(os.path.join(root, "en", OPENSCQ30_FTL))
        self.by_english = {}
        for key, text in self.english.items():
            self.by_english.setdefault(text, key)

    def name(self, ident):
        """ambientSoundMode → the name of ambient-sound-mode, or the id spelled out."""
        key = VENDOR_KEYS.get(ident) or ftl_key(ident)
        if key in self.messages:
            return self.messages[key]
        words = key.replace("-", " ")
        return words[:1].upper() + words[1:]

    def option(self, ident, label):
        """An option's English label from openscq30 in the user's language.

        Only labels that are one of openscq30's messages are translated: device names and
        the like stay as they are."""
        m = VENDOR_DURATION.match(ident)
        if m:
            n = int(m.group(1))
            if m.group(2) == "s":
                return ngettext("{n} second", "{n} seconds", n).format(n=n)
            if m.group(2) == "m":
                return ngettext("{n} minute", "{n} minutes", n).format(n=n)
            return ngettext("{n} hour", "{n} hours", n).format(n=n)
        if not re.fullmatch(r"[A-Za-z][A-Za-z0-9]*", ident):
            return label  # an address or a name, not one of openscq30's ids
        key = ftl_key(ident)
        if key not in self.english or label not in (ident, self.english[key]):
            # RnB is rnb, not rn-b: the English label names the message too
            key = self.by_english.get(label)
        return self.messages.get(key, label) if key else label


# ----- running programs -----

def run(argv, timeout=10):
    """Output of a short program, or None when it failed."""
    try:
        r = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired) as e:
        log(f"{argv[0]}: {e}")
        return None
    if r.returncode != 0:
        log(f"{' '.join(argv)}: exit {r.returncode}: {r.stderr.strip()[:300]}")
        return None
    return r.stdout


def run_async(argv, timeout, done):
    """Runs a program without blocking; done(stdout or None, stderr) once it ends."""
    try:
        proc = Gio.Subprocess.new(argv, Gio.SubprocessFlags.STDOUT_PIPE
                                  | Gio.SubprocessFlags.STDERR_PIPE)
    except GLib.Error as e:
        done(None, e.message)
        return
    state = {"timer": 0}

    def on_timeout():
        state["timer"] = 0
        proc.force_exit()
        return False

    def on_done(p, result):
        if state["timer"]:
            GLib.source_remove(state["timer"])
        try:
            _ok, out, err = p.communicate_utf8_finish(result)
        except GLib.Error as e:
            done(None, e.message)
            return
        if p.get_if_exited() and p.get_exit_status() == 0:
            done(out, err)
        else:
            done(None, (err or "").strip() or "timed out")

    state["timer"] = GLib.timeout_add_seconds(timeout, on_timeout)
    proc.communicate_utf8_async(None, None, on_done)


# ----- codec (PipeWire through pactl) -----

def codec_of(description):
    """'High Fidelity Playback (A2DP Sink, codec AAC)' → AAC (PipeWire's text, also translated)"""
    m = re.search(r"\bcodec\s+([^(),]+)\)\s*$", description or "", re.IGNORECASE)
    return m.group(1).strip() if m else ""


def find_card(cards, address):
    for card in cards:
        if (card.get("properties") or {}).get("api.bluez5.address") == address:
            return card
    return None


def codec_setting(card):
    """The codec as a select over the card's A2DP profiles; None without A2DP."""
    profiles = card.get("profiles") or {}
    names, labels = [], []
    for name, p in sorted(profiles.items(), key=lambda kv: -(kv[1].get("priority") or 0)):
        if not name.startswith("a2dp-sink") or p.get("available") is False:
            continue
        codec = codec_of(p.get("description"))
        if name == "a2dp-sink":
            label = _("Automatic ({codec})").format(codec=codec) if codec else _("Automatic")
        else:
            label = codec or name
        names.append(name)
        labels.append(label)
    if not names:
        return None
    active = card.get("active_profile") or ""
    return setting("audio.codec", "audio", _("Audio"), "select", _("Codec"),
                   GLib.Variant("s", active if active in names else ""),
                   options=GLib.Variant("as", names),
                   option_labels=GLib.Variant("as", labels),
                   sensitive=GLib.Variant("b", active in names),
                   subtitle=GLib.Variant(
                       "s", "" if active in names else _("Not while a call uses the headset")))


def list_cards():
    out = run(["pactl", "-f", "json", "list", "cards"])
    if out is None:
        return []
    try:
        cards = json.loads(out)
    except ValueError:
        return []
    return cards if isinstance(cards, list) else []


# ----- the phone's equalizer -----

def preset_labels():
    return {
        "flat": _("Flat"),
        "bass": _("More Bass"),
        "treble": _("More Treble"),
        "voice": _("Voice"),
        "loudness": _("Loudness"),
        "soft": _("Softer Highs"),
        "custom": _("Custom"),
    }


def clamp_bands(values):
    if len(values) != len(EQ_BANDS):
        raise HeadsetError("InvalidValue", "wrong number of bands")
    return [max(-EQ_LIMIT, min(EQ_LIMIT, int(v))) for v in values]


def preset_of(bands):
    for name, values in EQ_PRESETS.items():
        if list(values) == list(bands):
            return name
    return "custom"


def eq_node_name(address):
    return "plinius_eq." + address.replace(":", "_")


def eq_controls(bands):
    """The filter graph's control values: band gains in dB and a preamp against clipping."""
    controls = {f"eq_{i + 1}:Gain": v / 10 for i, v in enumerate(bands)}
    peak = max([0] + list(bands)) / 10
    controls["pre:Mult"] = round(math.pow(10, -peak / 20), 4)
    return controls


def spa_string(text):
    return json.dumps(text, ensure_ascii=False)


def eq_dropin(address, name, bands):
    """A drop-in of plinius-eq.conf: one filter chain in front of this device only."""
    controls = eq_controls(bands)
    nodes = [f'{{ type = builtin name = pre label = linear control = {{ "Mult" = '
             f'{controls["pre:Mult"]} }} }}']
    for i, hz in enumerate(EQ_BANDS):
        label = ("bq_lowshelf" if i == 0 else
                 "bq_highshelf" if i == len(EQ_BANDS) - 1 else "bq_peaking")
        nodes.append(f'{{ type = builtin name = eq_{i + 1} label = {label} control = {{ '
                     f'"Freq" = {float(hz)} "Q" = {EQ_Q} "Gain" = {bands[i] / 10} }} }}')
    links = [f'{{ output = "{a}:Out" input = "{b}:In" }}'
             for a, b in zip(["pre"] + [f"eq_{i}" for i in range(1, len(EQ_BANDS))],
                             [f"eq_{i}" for i in range(1, len(EQ_BANDS) + 1)])]
    node = eq_node_name(address)
    description = _("Equalizer for {name}").format(name=name)
    return f"""# Written by plinius-headset: the equalizer of {address}
context.modules = [
  {{ name = libpipewire-module-filter-chain
    args = {{
      node.description = {spa_string(description)}
      media.name = {spa_string(description)}
      filter.graph = {{
        nodes = [
          {(chr(10) + '          ').join(nodes)}
        ]
        links = [
          {(chr(10) + '          ').join(links)}
        ]
      }}
      audio.channels = 2
      audio.position = [ FL FR ]
      capture.props = {{
        node.name = "{node}"
        media.class = Audio/Sink
        filter.smart = true
        filter.smart.name = "plinius-eq.{address}"
        filter.smart.target = {{ api.bluez5.address = "{address}" media.class = "Audio/Sink" }}
      }}
      playback.props = {{
        node.name = "{node}.out"
        node.passive = true
      }}
    }}
  }}
]
"""


class Equalizers:
    """The settings per device (JSON) and the filter host's drop-ins made from them."""

    def __init__(self, base=None):
        base = base or config_dir()
        self.state_path = os.path.join(base, "plinius-headset", "equalizers.json")
        self.dropin_dir = os.path.join(base, "pipewire", "plinius-eq.conf.d")
        self.state = self.load()

    def load(self):
        try:
            with open(self.state_path, encoding="utf-8") as f:
                state = json.load(f)
        except (OSError, ValueError):
            return {}
        out = {}
        for address, entry in state.items() if isinstance(state, dict) else ():
            try:
                bands = clamp_bands(entry.get("bands", EQ_PRESETS["flat"]))
            except (HeadsetError, TypeError, ValueError, AttributeError):
                continue
            if valid_address(address):
                out[address] = {"enabled": bool(entry.get("enabled")), "bands": bands,
                                "name": str(entry.get("name") or address)}
        return out

    def save(self):
        os.makedirs(os.path.dirname(self.state_path), exist_ok=True)
        tmp = self.state_path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            json.dump(self.state, f, indent=1, sort_keys=True)
        os.replace(tmp, self.state_path)

    def entry(self, address):
        return self.state.get(address) or {"enabled": False,
                                           "bands": list(EQ_PRESETS["flat"]), "name": address}

    def dropin_path(self, address):
        return os.path.join(self.dropin_dir, address.replace(":", "_") + ".conf")

    def write_dropin(self, address):
        entry = self.entry(address)
        path = self.dropin_path(address)
        if not entry["enabled"]:
            try:
                os.unlink(path)
            except FileNotFoundError:
                pass
            return
        os.makedirs(self.dropin_dir, exist_ok=True)
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as f:
            f.write(eq_dropin(address, entry["name"], entry["bands"]))
        os.replace(tmp, path)

    def settings(self, address):
        entry = self.entry(address)
        labels = preset_labels()
        preset = preset_of(entry["bands"])
        names = list(EQ_PRESETS) + (["custom"] if preset == "custom" else [])
        cat = _("Equalizer")
        return [
            setting("eq.enabled", "equalizer", cat, "toggle", _("Equalizer on the Phone"),
                    GLib.Variant("b", entry["enabled"]),
                    subtitle=GLib.Variant("s", _("Shapes the sound before it is sent"))),
            setting("eq.preset", "equalizer", cat, "select", _("Preset"),
                    GLib.Variant("s", preset),
                    options=GLib.Variant("as", names),
                    option_labels=GLib.Variant("as", [labels[n] for n in names]),
                    sensitive=GLib.Variant("b", entry["enabled"])),
            setting("eq.bands", "equalizer", cat, "equalizer", _("Bands"),
                    GLib.Variant("ai", entry["bands"]),
                    bands=GLib.Variant("ai", list(EQ_BANDS)),
                    min=GLib.Variant("i", -EQ_LIMIT), max=GLib.Variant("i", EQ_LIMIT),
                    fraction_digits=GLib.Variant("i", 1),
                    sensitive=GLib.Variant("b", entry["enabled"])),
        ]

    def set(self, address, sid, value, name):
        """Changes one setting; returns True when the filter host must restart."""
        entry = dict(self.entry(address))
        entry["name"] = name or entry["name"]
        restart = False
        if sid == "eq.enabled":
            entry["enabled"] = bool(value)
            restart = True
        elif sid == "eq.preset":
            if value not in EQ_PRESETS:
                raise HeadsetError("InvalidValue", f"no preset {value}")
            entry["bands"] = list(EQ_PRESETS[value])
        elif sid == "eq.bands":
            entry["bands"] = clamp_bands(value)
        else:
            raise HeadsetError("NoSuchSetting", sid)
        self.state[address] = entry
        self.save()
        self.write_dropin(address)
        return restart

    def apply_live(self, address):
        """New band values to a running filter, without a gap in the sound."""
        node_id = find_node_id(eq_node_name(address))
        if node_id is None:
            return False
        controls = eq_controls(self.entry(address)["bands"])
        params = " ".join(f'"{k}" {v}' for k, v in controls.items())
        return run(["pw-cli", "set-param", str(node_id), "Props",
                    f"{{ params = [ {params} ] }}"]) is not None


def find_node_id(node_name):
    out = run(["pw-dump"])
    if out is None:
        return None
    try:
        objects = json.loads(out)
    except ValueError:
        return None
    for o in objects if isinstance(objects, list) else ():
        props = ((o.get("info") or {}).get("props") or {})
        if props.get("node.name") == node_name:
            return o.get("id")
    return None


def restart_eq_host():
    run(["systemctl", "--user", "restart", EQ_UNIT])


# ----- Soundcore through openscq30 -----

def soundcore_model(uuids, models):
    """The openscq30 model of a device from its Soundcore service UUID, or None."""
    for uuid in uuids:
        uuid = uuid.lower()
        if SOUNDCORE_UUID.match(uuid):
            digits = uuid[-4:]
            for model in models:
                if model.lower().endswith(digits):
                    return model
    return None


def vendor_value(kind, raw):
    """openscq30's {type, value} as the page's GLib value."""
    value = (raw or {}).get("value")
    if kind == "toggle":
        return GLib.Variant("b", bool(value))
    if kind == "range":
        return GLib.Variant("i", int(value or 0))
    if kind == "select":
        return GLib.Variant("s", "" if value is None else str(value))
    if kind == "equalizer":
        return GLib.Variant("ai", [int(v) for v in value or []])
    if kind == "info":
        if isinstance(value, list):
            value = ", ".join(str(v) for v in value)
        return GLib.Variant("s", "" if value is None else str(value))
    return None


def vendor_settings(listing, values, names):
    """openscq30's list-settings and setting --get output as the page's settings."""
    by_id = {v.get("settingId"): v.get("value") for v in values}
    out = []
    for category in listing:
        cid = category.get("categoryId") or ""
        clabel = names.name(cid)
        for s in category.get("settings") or []:
            sid = s.get("settingId") or ""
            kind = VENDOR_TYPES.get(s.get("type"))
            if not kind or not sid:
                continue
            info = s.get("setting") or {}
            extra = {}
            if kind == "select":
                options = [str(o) for o in info.get("options") or []]
                labels = [str(o) for o in info.get("localizedOptions") or options]
                if len(labels) != len(options):
                    labels = options
                labels = [names.option(o, label) for o, label in zip(options, labels)]
                if s.get("type") == "optionalSelect":
                    options, labels = [""] + options, [names.name("none")] + labels
                extra["options"] = GLib.Variant("as", options)
                extra["option_labels"] = GLib.Variant("as", labels)
            elif kind == "range":
                extra["min"] = GLib.Variant("i", int(info.get("start", 0)))
                extra["max"] = GLib.Variant("i", int(info.get("end", 0)))
                extra["step"] = GLib.Variant("i", int(info.get("step", 1)) or 1)
            elif kind == "equalizer":
                extra["bands"] = GLib.Variant("ai", [int(b) for b in info.get("bandHz") or []])
                extra["min"] = GLib.Variant("i", int(info.get("min", 0)))
                extra["max"] = GLib.Variant("i", int(info.get("max", 0)))
                extra["fraction_digits"] = GLib.Variant("i", int(info.get("fractionDigits", 0)))
            value = None if kind == "action" else vendor_value(kind, by_id.get(sid))
            out.append(setting("vendor." + sid, cid, clabel, kind, names.name(sid), value,
                               **extra))
    return out


def vendor_arg(kind, value):
    """A page value as openscq30's --set text."""
    if kind == "toggle":
        return "true" if value else "false"
    if kind == "equalizer":
        return ",".join(str(int(v)) for v in value)
    return str(value)


class Soundcore:
    name = "Soundcore"

    def __init__(self):
        self.models = None
        self.listings = {}  # address → list-settings output
        self.kinds = {}  # address → {setting id: page type}
        self.paired = None
        self.names = None

    def known_models(self):
        if self.models is None:
            out = run([OPENSCQ30, "list-models", "--json"])
            try:
                self.models = [m["model"] for m in json.loads(out or "[]")]
            except (ValueError, TypeError, KeyError):
                self.models = []
        return self.models

    def model(self, uuids):
        if not any(SOUNDCORE_UUID.match(u.lower()) for u in uuids):
            return None
        return soundcore_model(uuids, self.known_models())

    def ensure_paired(self, address, model):
        """openscq30 keeps its own list of devices and their models."""
        if self.paired is None:
            out = run([OPENSCQ30, "paired-devices", "list", "--json"])
            try:
                self.paired = {d["macAddress"]: d["model"] for d in json.loads(out or "[]")}
            except (ValueError, TypeError, KeyError):
                self.paired = {}
        if self.paired.get(address) == model:
            return True
        if address in self.paired:
            run([OPENSCQ30, "paired-devices", "remove", "-a", address])
        if run([OPENSCQ30, "paired-devices", "add", "-a", address, "-m", model]) is None:
            return False
        self.paired[address] = model
        return True

    def vendor_names(self):
        if self.names is None:
            self.names = VendorNames()
        return self.names

    def get(self, address, model, done):
        """done(settings) or done(None, error) after one or two connections."""
        if not self.ensure_paired(address, model):
            done(None, _("The headphones could not be registered"))
            return

        def with_listing(listing):
            ids = self.readable_ids(listing)
            self.kinds[address] = {s.get("settingId"): VENDOR_TYPES.get(s.get("type"))
                                   for c in listing for s in c.get("settings") or []}
            argv = [OPENSCQ30, "device", "-a", address, "setting", "--json"]
            for sid in ids:
                argv += ["-g", sid]
            if not ids:
                done(vendor_settings(listing, [], self.vendor_names()))
                return

            def on_values(out, err):
                values = parse_json_list(out)
                if values is None:
                    self.listings.pop(address, None)
                    done(None, _("The headphones do not answer"))
                    return
                done(vendor_settings(listing, values, self.vendor_names()))

            run_async(argv, VENDOR_TIMEOUT, on_values)

        if address in self.listings:
            with_listing(self.listings[address])
            return

        def on_listing(out, err):
            listing = parse_json_list(out)
            if listing is None:
                done(None, _("The headphones do not answer"))
                return
            self.listings[address] = listing
            with_listing(listing)

        run_async([OPENSCQ30, "device", "-a", address, "list-settings", "--json"],
                  VENDOR_TIMEOUT, on_listing)

    def set(self, address, model, sid, value, done):
        kind = (self.kinds.get(address) or {}).get(sid)
        if kind is None:
            done(None, _("Unknown setting"))
            return
        listing = self.listings.get(address) or []
        arg = sid if kind == "action" else f"{sid}={vendor_arg(kind, value)}"
        # Set, then read everything again in the same connection: one setting can change others
        argv = [OPENSCQ30, "device", "-a", address, "setting", "--json", "-s", arg]
        for other in self.readable_ids(listing):
            argv += ["-g", other]

        def on_set(out, err):
            values = parse_json_list(out)
            if values is None:
                # Which settings there are may have changed with it: list them anew next time
                self.listings.pop(address, None)
                done(None, _("The headphones did not take the setting"))
                return
            done(vendor_settings(listing, values, self.vendor_names()))

        run_async(argv, VENDOR_TIMEOUT, on_set)

    @staticmethod
    def readable_ids(listing):
        return [s.get("settingId") for c in listing for s in c.get("settings") or []
                if s.get("type") in VENDOR_TYPES and s.get("type") != "action"
                and s.get("settingId")]


def parse_json_list(out):
    if out is None:
        return None
    try:
        data = json.loads(out)
    except ValueError:
        return None
    return data if isinstance(data, list) else None


# ----- the service -----

class Headset:
    def __init__(self, conn, system=None, equalizers=None, vendors=None, on_idle=None):
        self.conn = conn
        self.system = system
        self.equalizers = equalizers or Equalizers()
        self.vendors = vendors if vendors is not None else [Soundcore()]
        self.busy = set()  # addresses with a vendor call running
        self.on_idle = on_idle
        self.idle_id = 0
        self.node = Gio.DBusNodeInfo.new_for_xml(INTERFACE_XML)
        if conn is not None:
            conn.register_object(OBJECT_PATH, self.node.interfaces[0], self.on_method_call,
                                 None, None)
        self.schedule_idle_exit()

    def schedule_idle_exit(self):
        """Started on demand by the device page; gone a while after the last call."""
        if self.on_idle is None:
            return
        if self.idle_id:
            GLib.source_remove(self.idle_id)
        self.idle_id = GLib.timeout_add_seconds(IDLE_EXIT_SECONDS, self.idle_timeout)

    def idle_timeout(self):
        self.idle_id = 0
        if self.busy:
            self.schedule_idle_exit()
        else:
            self.on_idle()
        return False

    # BlueZ

    def bus(self):
        if self.system is None:
            self.system = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
        return self.system

    def device_property(self, address, iface, name):
        try:
            reply = self.bus().call_sync(
                BLUEZ, device_path(address), "org.freedesktop.DBus.Properties", "Get",
                GLib.Variant("(ss)", (iface, name)), GLib.VariantType("(v)"),
                Gio.DBusCallFlags.NONE, 2000, None)
        except GLib.Error:
            return None
        return reply.unpack()[0]

    def device_name(self, address):
        return (self.device_property(address, BLUEZ_DEVICE_IFACE, "Alias")
                or self.device_property(address, BLUEZ_DEVICE_IFACE, "Name") or address)

    def uuids(self, address):
        return self.device_property(address, BLUEZ_DEVICE_IFACE, "UUIDs") or []

    def vendor_for(self, address):
        uuids = self.uuids(address)
        for vendor in self.vendors:
            model = vendor.model(uuids)
            if model:
                return vendor, model
        return None, None

    # settings

    def audio_settings(self, address):
        if AUDIO_SINK_UUID not in [u.lower() for u in self.uuids(address)]:
            return []
        out = []
        card = find_card(list_cards(), address)
        if card is not None:
            codec = codec_setting(card)
            if codec is not None:
                out.append(codec)
        battery = self.device_property(address, BLUEZ_BATTERY_IFACE, "Percentage")
        if battery is not None:
            out.append(setting("audio.battery", "audio", _("Audio"), "info", _("Battery"),
                               GLib.Variant("s", f"{int(battery)} %")))
        return out + self.equalizers.settings(address)

    def set_audio(self, address, sid, value):
        if sid == "audio.codec":
            card = find_card(list_cards(), address)
            if card is None or value not in (card.get("profiles") or {}) \
                    or not str(value).startswith("a2dp-sink"):
                raise HeadsetError("InvalidValue", f"no codec {value}")
            if run(["pactl", "set-card-profile", card["name"], value]) is None:
                raise HeadsetError("Failed", _("The codec could not be changed"))
            return
        if self.equalizers.set(address, sid, value, self.device_name(address)):
            restart_eq_host()
        else:
            self.equalizers.apply_live(address)

    # D-Bus

    def on_method_call(self, conn, sender, path, iface, method, params, invocation):
        self.schedule_idle_exit()
        try:
            self.dispatch(method, params.unpack(), invocation)
        except HeadsetError as e:
            invocation.return_dbus_error(ERROR_PREFIX + e.name, str(e))

    def dispatch(self, method, args, invocation):
        address = args[0]
        if not valid_address(address):
            raise HeadsetError("InvalidAddress", f"not a Bluetooth address: {address}")
        if method == "HasVendorSettings":
            vendor, _model = self.vendor_for(address)
            invocation.return_value(GLib.Variant("(s)", (vendor.name if vendor else "",)))
        elif method == "GetSettings":
            group = args[1]
            if group == "audio":
                self.reply(invocation, self.audio_settings(address))
            elif group == "vendor":
                self.vendor_call(address, invocation, None, None)
            else:
                raise HeadsetError("InvalidGroup", group)
        elif method == "SetSetting":
            sid, value = args[1], args[2]
            if sid.startswith("vendor."):
                self.vendor_call(address, invocation, sid[len("vendor."):], value)
                return
            self.set_audio(address, sid, value)
            self.reply(invocation, self.audio_settings(address))
            self.emit_changed(address, "audio")
        else:  # pragma: no cover - the interface has no other method
            raise HeadsetError("Failed", method)

    def vendor_call(self, address, invocation, sid, value):
        vendor, model = self.vendor_for(address)
        if vendor is None:
            self.reply(invocation, [])
            return
        if address in self.busy:
            raise HeadsetError("Busy", _("The headphones are still busy"))
        self.busy.add(address)

        def done(settings, error=None):
            self.busy.discard(address)
            if settings is None:
                invocation.return_dbus_error(ERROR_PREFIX + "Unreachable", error or "")
                return
            self.reply(invocation, settings)
            if sid is not None:
                self.emit_changed(address, "vendor")

        if sid is None:
            vendor.get(address, model, done)
        else:
            vendor.set(address, model, sid, value, done)

    def reply(self, invocation, settings):
        invocation.return_value(GLib.Variant("(aa{sv})", (settings,)))

    def emit_changed(self, address, group):
        if self.conn is not None:
            self.conn.emit_signal(None, OBJECT_PATH, IFACE, "Changed",
                                  GLib.Variant("(ss)", (address, group)))


def main():  # pragma: no cover - needs a session bus and a main loop
    locale.setlocale(locale.LC_ALL, "")
    loop = GLib.MainLoop()
    service = {}

    def on_bus_acquired(conn, name):
        service["s"] = Headset(conn, on_idle=loop.quit)

    def on_name_lost(conn, name):
        log("The bus name is taken, exiting")
        loop.quit()

    Gio.bus_own_name(Gio.BusType.SESSION, BUS_NAME, Gio.BusNameOwnerFlags.NONE,
                     on_bus_acquired, None, on_name_lost)
    for signum in (signal.SIGTERM, signal.SIGINT):
        GLibUnix.signal_add(GLib.PRIORITY_DEFAULT, signum, lambda: loop.quit() or False)
    loop.run()


if __name__ == "__main__":
    main()
