#!/usr/bin/python3
# KemmOS Voix 1.0.0 — raccourcis clavier de la voix (raccourcis personnalisés de GNOME, pour l'utilisateur) :
#   Ctrl+Alt+L : lire à voix haute le texte copié (kemmos-lire --presse-papiers)
#   Ctrl+Alt+D : dictée (kemmos-dictee --ecouter)
# usage : kemmos-voix-raccourcis oui|non|etat|premiere-fois
#   premiere-fois (ouverture de session) : pose les raccourcis une seule fois par utilisateur ; si on les coupe
#   ensuite (KemmOS Style › Confort), ils ne reviennent pas.
# Un raccourci déjà pris par un autre raccourci personnalisé n'est pas posé (pas de doublon).
import os
import sys

from gi.repository import Gio

MEDIA = "org.gnome.settings-daemon.plugins.media-keys"
PERSO = MEDIA + ".custom-keybinding"
BASE = "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/"
RACCOURCIS = [  # (nom du chemin, nom affiché, commande, touches)
    ("kemmos-lire", "Lire à voix haute (KemmOS)", "kemmos-lire --presse-papiers", "<Control><Alt>l"),
    ("kemmos-dictee", "Dictée (KemmOS)", "kemmos-dictee --ecouter", "<Control><Alt>d"),
]
FAIT = os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"), "kemmos-voix",
                    "raccourcis-poses")


def schema_present(nom):
    source = Gio.SettingsSchemaSource.get_default()
    return bool(source and source.lookup(nom, True))


def perso(chemin):
    return Gio.Settings.new_with_path(PERSO, chemin)


def chemins_kemmos():
    return [BASE + nom + "/" for nom, *_r in RACCOURCIS]


def etat():
    m = Gio.Settings.new(MEDIA)
    return all(c in m.get_strv("custom-keybindings") for c in chemins_kemmos())


def poser():
    m = Gio.Settings.new(MEDIA)
    liste = m.get_strv("custom-keybindings")
    pris = {perso(c).get_string("binding").lower() for c in liste if c not in chemins_kemmos()}
    for nom, titre, commande, touches in RACCOURCIS:
        chemin = BASE + nom + "/"
        if touches.lower() in pris:
            print(f"{touches} déjà pris : raccourci « {titre} » non posé")
            continue
        s = perso(chemin)
        s.set_string("name", titre)
        s.set_string("command", commande)
        s.set_string("binding", touches)
        if chemin not in liste:
            liste.append(chemin)
    m.set_strv("custom-keybindings", liste)
    Gio.Settings.sync()


def retirer():
    m = Gio.Settings.new(MEDIA)
    m.set_strv("custom-keybindings", [c for c in m.get_strv("custom-keybindings") if c not in chemins_kemmos()])
    for c in chemins_kemmos():
        s = perso(c)
        for cle in ("name", "command", "binding"):
            s.reset(cle)
    Gio.Settings.sync()


def main(arg):
    if not schema_present(MEDIA):
        print("raccourcis de GNOME absents")
        return 1
    if arg == "etat":
        print("oui" if etat() else "non")
    elif arg == "oui":
        poser()
    elif arg == "non":
        retirer()
    elif arg == "premiere-fois":
        if not os.path.exists(FAIT):
            poser()
            os.makedirs(os.path.dirname(FAIT), exist_ok=True)
            open(FAIT, "w").close()
    else:
        print("usage : kemmos-voix-raccourcis oui|non|etat|premiere-fois", file=sys.stderr)
        return 2
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else ""))
