#!/usr/bin/python3
"""ft-pause: pause Frametop for a VR game, so it leaves the CPU and GPU to the game, or resume it.

  ft-pause on|off|toggle   pause or resume (input/game_pause.py has what pausing stops)
  ft-pause status          the pause state, as JSON (the default)

The input relay does it (frametop-input-relay.service). So do the pause_toggle action, the
controller gesture (by default both thumbsticks clicked together twice), and, with auto pause on,
a VR game starting; Frametop Input Settings has the settings, on its Game optimization page.
"""

import json
import os
import socket
import sys


def ask(msg, timeout=2.0):
    s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM | socket.SOCK_CLOEXEC)
    s.bind(f"\0ft_pause.{os.getpid()}")
    s.settimeout(timeout)
    try:
        s.sendto(msg.encode(), "\0frametop_relay")
        return json.loads(s.recv(65536))
    except ConnectionRefusedError:
        sys.exit("the input relay isn't running (frametop-input-relay.service)")
    except (socket.timeout, ValueError):
        sys.exit("no answer from the input relay (an older one, without pausing?)")
    finally:
        s.close()


def main():
    cmd = sys.argv[1] if len(sys.argv) > 1 else "status"
    if cmd in ("on", "off", "toggle"):
        r = ask(f"pause {cmd} command")
        print("Frametop paused" if r.get("paused") else "Frametop running")
    elif cmd == "status":
        print(json.dumps(ask("pause ?"), indent=1))
    else:
        sys.exit(__doc__)


if __name__ == "__main__":
    main()
