#!/usr/bin/python3
# blob:summary=Control Razer keyboard lighting through OpenRazer: effect, colour, brightness and game mode
# blob:args=[status|select <serial>|brightness <0-100>|effect <name>|colour <hex>|random on|off|speed fast|normal|slow|direction left|right|lights on|off|toggle|game-mode on|off]
# blob:group=hardware

from __future__ import annotations

import json
import os
import re
import sys
from pathlib import Path
from typing import Any

STATE_DIRECTORY = Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local" / "state"))) / "blob"
SETTINGS_FILE = STATE_DIRECTORY / "razer.json"
EFFECTS = ("static", "spectrum", "wave", "breath", "reactive", "starlight", "ripple", "none")
COLOUR_EFFECTS = ("static", "breath", "reactive", "starlight", "ripple")
RANDOM_EFFECTS = ("breath", "starlight", "ripple")
SPEED_EFFECTS = ("reactive", "starlight")
DAEMON_EFFECT_NAMES = {
  "static": ("static", False),
  "spectrum": ("spectrum", False),
  "wave": ("wave", False),
  "breathSingle": ("breath", False),
  "breathDual": ("breath", False),
  "breathTriple": ("breath", False),
  "breathRandom": ("breath", True),
  "reactive": ("reactive", False),
  "starlightSingle": ("starlight", False),
  "starlightDual": ("starlight", False),
  "starlightRandom": ("starlight", True),
  "ripple": ("ripple", False),
  "rippleRandomColour": ("ripple", True),
  "rippleRandom": ("ripple", True),
  "none": ("none", False),
}
DEFAULT_SETTINGS = {"device": "", "effect": "spectrum", "colour": "#00ff00", "random": False, "speed": "normal", "direction": "right", "lastEffect": "spectrum"}
USAGE = "Usage: blob-razer [status|select <serial>|brightness <0-100>|effect <name>|colour <hex>|random on|off|speed fast|normal|slow|direction left|right|lights on|off|toggle|game-mode on|off]"


def read_settings() -> dict[str, Any]:
  settings = dict(DEFAULT_SETTINGS)
  try:
    saved = json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))
  except (OSError, ValueError):
    saved = {}
  if isinstance(saved, dict):
    settings.update({key: value for key, value in saved.items() if key in DEFAULT_SETTINGS})
  return settings


def write_settings(settings: dict[str, Any]) -> None:
  SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
  temporary = SETTINGS_FILE.with_suffix(".tmp")
  temporary.write_text(json.dumps(settings) + "\n", encoding="utf-8")
  temporary.replace(SETTINGS_FILE)


def load_devices() -> tuple[list[Any], str]:
  try:
    from openrazer.client import DeviceManager
  except ImportError:
    return [], "Install python-openrazer and openrazer-daemon"
  try:
    manager = DeviceManager()
    manager.sync_effects = False
    return list(manager.devices), ""
  except Exception as error:
    return [], f"The OpenRazer daemon is not running ({type(error).__name__})"


def lighting_devices(devices: list[Any]) -> list[Any]:
  return [device for device in devices if device.has("lighting") or device.has("brightness")]


def pick_device(devices: list[Any], settings: dict[str, Any]) -> Any | None:
  for device in devices:
    if device.serial == settings["device"]:
      return device
  keyboards = [device for device in devices if device.type == "keyboard"]
  return (keyboards or devices or [None])[0]


def rgb(colour: str) -> tuple[int, int, int]:
  value = colour.lstrip("#")
  return int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16)


def constant(name: str, fallback: Any) -> Any:
  try:
    from openrazer.client import constants
  except ImportError:
    return fallback
  return getattr(constants, name, fallback)


def apply_effect(device: Any, settings: dict[str, Any]) -> bool:
  fx = device.fx
  effect = settings["effect"]
  red, green, blue = rgb(settings["colour"])
  random = settings["random"]
  speed = settings["speed"]
  if effect == "static" and fx.has("static"):
    return fx.static(red, green, blue)
  if effect == "spectrum" and fx.has("spectrum"):
    return fx.spectrum()
  if effect == "wave" and fx.has("wave"):
    return fx.wave(constant("WAVE_LEFT", 2) if settings["direction"] == "left" else constant("WAVE_RIGHT", 1))
  if effect == "breath":
    if random and fx.has("breath_random"):
      return fx.breath_random()
    if fx.has("breath_single"):
      return fx.breath_single(red, green, blue)
  if effect == "reactive" and fx.has("reactive"):
    times = {"fast": constant("REACTIVE_500MS", 1), "normal": constant("REACTIVE_1000MS", 2), "slow": constant("REACTIVE_2000MS", 4)}
    return fx.reactive(red, green, blue, times.get(speed, times["normal"]))
  if effect == "starlight":
    times = {"fast": constant("STARLIGHT_FAST", 1), "normal": constant("STARLIGHT_NORMAL", 2), "slow": constant("STARLIGHT_SLOW", 3)}
    time = times.get(speed, times["normal"])
    if random and fx.has("starlight_random"):
      return fx.starlight_random(time)
    if fx.has("starlight_single"):
      return fx.starlight_single(red, green, blue, time)
  if effect == "ripple":
    refresh = constant("RIPPLE_REFRESH_RATE", 0.05)
    if random and fx.has("ripple_random"):
      return fx.ripple_random(refresh)
    if fx.has("ripple"):
      return fx.ripple(red, green, blue, refresh)
  if effect == "none" and fx.has("none"):
    return fx.none()
  return False


def current_effect(device: Any, settings: dict[str, Any]) -> tuple[str, bool, str]:
  effect, random, colour = settings["effect"], settings["random"], settings["colour"]
  try:
    reported = str(device.fx.effect)
    if reported in DAEMON_EFFECT_NAMES:
      effect, random = DAEMON_EFFECT_NAMES[reported]
    colours = bytes(device.fx.colors)
    if len(colours) >= 3 and effect in COLOUR_EFFECTS and not random:
      colour = "#{:02x}{:02x}{:02x}".format(colours[0], colours[1], colours[2])
  except Exception:
    pass
  return effect, random, colour


def supported_effects(device: Any) -> list[str]:
  fx = device.fx
  checks = {
    "static": ("static",),
    "spectrum": ("spectrum",),
    "wave": ("wave",),
    "breath": ("breath_single", "breath_random"),
    "reactive": ("reactive",),
    "starlight": ("starlight_single", "starlight_random"),
    "ripple": ("ripple", "ripple_random"),
    "none": ("none",),
  }
  return [effect for effect in EFFECTS if any(fx.has(name) for name in checks[effect])]


def device_summary(device: Any) -> dict[str, str]:
  return {"serial": str(device.serial), "name": str(device.name), "type": str(device.type)}


def status() -> dict[str, Any]:
  settings = read_settings()
  devices, error = load_devices()
  devices = lighting_devices(devices)
  device = pick_device(devices, settings)
  result: dict[str, Any] = {
    "available": error == "",
    "error": error,
    "devices": [device_summary(entry) for entry in devices],
    "present": device is not None,
  }
  if device is None:
    return result
  effect, random, colour = current_effect(device, settings)
  result.update({
    "serial": str(device.serial),
    "name": str(device.name),
    "type": str(device.type),
    "firmware": str(getattr(device, "firmware_version", "")),
    "layout": str(getattr(device, "keyboard_layout", "")) if device.has("keyboard_layout") else "",
    "brightness": round(float(device.brightness)) if device.has("brightness") else None,
    "effect": effect,
    "random": random,
    "colour": colour,
    "speed": settings["speed"],
    "direction": settings["direction"],
    "effects": supported_effects(device),
    "gameMode": bool(device.game_mode_led) if device.has("game_mode_led") else None,
    "lightsOn": effect != "none",
  })
  return result


def with_device(settings: dict[str, Any]) -> Any:
  devices, error = load_devices()
  device = pick_device(lighting_devices(devices), settings)
  if device is None:
    print(error or "No Razer device found", file=sys.stderr)
    sys.exit(1)
  return device


def change_effect(device: Any, settings: dict[str, Any], **changes: Any) -> int:
  effect, random, colour = current_effect(device, settings)
  settings.update({"effect": effect, "random": random, "colour": colour})
  settings.update(changes)
  if settings["effect"] != "none":
    settings["lastEffect"] = settings["effect"]
  if not apply_effect(device, settings):
    print(f"{device.name} does not support that effect", file=sys.stderr)
    return 1
  write_settings(settings)
  return 0


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "status"
  value = arguments[1].lower() if len(arguments) > 1 else ""
  if action == "status":
    print(json.dumps(status()))
    return 0
  if action in ("help", "--help", "-h"):
    print(USAGE)
    return 0
  settings = read_settings()
  if action == "select" and value:
    settings["device"] = arguments[1]
    write_settings(settings)
    return 0
  device = with_device(settings)
  if action == "brightness" and value.isdigit():
    device.brightness = max(0, min(100, int(value)))
    return 0
  if action == "effect" and value in EFFECTS:
    return change_effect(device, settings, effect=value)
  if action == "colour" and re.fullmatch(r"#?([0-9a-f]{2})?[0-9a-f]{6}", value):
    effect = current_effect(device, settings)[0]
    return change_effect(device, settings, colour="#" + value.lstrip("#")[-6:], random=False, effect=effect if effect in COLOUR_EFFECTS else "static")
  if action == "random" and value in ("on", "off"):
    return change_effect(device, settings, random=value == "on")
  if action == "speed" and value in ("fast", "normal", "slow"):
    return change_effect(device, settings, speed=value)
  if action == "direction" and value in ("left", "right"):
    return change_effect(device, settings, direction=value)
  if action in ("lights", "toggle"):
    lights_on = current_effect(device, settings)[0] != "none"
    turn_on = value == "on" if action == "lights" else not lights_on
    return change_effect(device, settings, effect=settings["lastEffect"] if turn_on else "none")
  if action == "game-mode" and value in ("on", "off") and device.has("game_mode_led"):
    device.game_mode_led = value == "on"
    return 0
  print("blob-razer does not understand: " + " ".join(arguments), file=sys.stderr)
  return 2


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