#!/usr/bin/env python3
# summary: Read or apply app notification preferences.
"""Notification preferences, without history or Do not disturb.

Usage: starchaser notifications export | apply --stdin
       starchaser notifications set-app NAME popups|sound on|off

export prints the saved preferences as JSON.
apply --stdin reads the same JSON format from standard input, for example:
  {"duration": 6, "position": "auto", "sound": true, "apps": {}}
duration is 0, 4, 6, or 10 seconds; position is auto, left, or right.
apps maps app names to optional popups and sound switches (true or false).
If the saved file can't be read, export says so; apply replaces it, keeping the old one as notifications.json.broken.
"""
import fcntl
import json
import os
import shutil
import stat
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_settings_schema as schema

SETTINGS = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "starchaser/notifications.json"
DEFAULTS = {"duration": 6, "position": "auto", "sound": True, "apps": {}}


class Plain(ValueError):
    """A problem worded for the person; only these messages are shown as written."""


def read():
    try:
        fd = os.open(SETTINGS, os.O_RDONLY | os.O_NOFOLLOW)
    except FileNotFoundError:
        return {}
    with os.fdopen(fd, "rb") as handle:
        try:
            schema.require(stat.S_ISREG(os.fstat(handle.fileno()).st_mode))
            value = schema.loads(handle.read(schema.MAX_BYTES + 1))
            schema.require(isinstance(value, dict))
        except ValueError:
            raise Plain("the saved file isn't valid") from None
    return value


def export():
    saved = read()
    try:
        return schema.payload("notifications", {key: saved.get(key, default) for key, default in DEFAULTS.items()})
    except ValueError:
        raise Plain("the saved file isn't valid") from None


def explain(value):
    """Say which setting is wrong, in plain words, before the general check."""
    if not isinstance(value, dict):
        raise Plain("expected a JSON object with duration, position, sound and apps")
    missing = [key for key in DEFAULTS if key not in value]
    if missing:
        raise Plain("missing " + ", ".join(missing))
    extra = sorted(str(key) for key in value if key not in DEFAULTS)
    if extra:
        raise Plain("unknown setting " + ", ".join(extra))
    if type(value["duration"]) is not int or value["duration"] not in (0, 4, 6, 10):
        raise Plain("duration must be 0, 4, 6 or 10 seconds")
    if value["position"] not in ("auto", "left", "right"):
        raise Plain("position must be auto, left or right")
    if type(value["sound"]) is not bool:
        raise Plain("sound must be true or false")
    if not isinstance(value["apps"], dict):
        raise Plain("apps must be a list of app names with true or false switches")


def apply(value):
    explain(value)
    try:
        schema.payload("notifications", value)
    except ValueError:
        raise Plain("one of the app entries isn't valid") from None
    SETTINGS.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    if SETTINGS.parent.is_symlink():
        raise Plain("the settings folder is a link")
    fd = os.open(SETTINGS.parent / ".notifications.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, "w") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        try:
            saved = read()
        except Plain:
            # A file that can't be read is kept aside (like input.lua.broken) and these settings start a fresh one,
            # so a hand-edit gone wrong can be put right through the tool. It is copied, not renamed away: the path
            # must stay written at every moment, or the taskbar's writer replaces a missing file with its defaults
            # and undoes these settings the moment they land.
            try:
                shutil.copyfile(SETTINGS, SETTINGS.with_name(SETTINGS.name + ".broken"))
            except OSError:
                pass
            saved = {}
        saved.update(value)  # Keep this computer's Do not disturb switch.
        write_saved(saved)


def write_saved(saved):
    handle, name = tempfile.mkstemp(prefix=".notifications.", suffix=".tmp", dir=SETTINGS.parent)
    try:
        with os.fdopen(handle, "w") as out:
            out.write(json.dumps(saved, sort_keys=True, ensure_ascii=True) + "\n")
            out.flush()
            os.fsync(out.fileno())
        os.replace(name, SETTINGS)
        directory = os.open(SETTINGS.parent, os.O_RDONLY | os.O_DIRECTORY)
        try:
            os.fsync(directory)
        finally:
            os.close(directory)
    finally:
        if os.path.exists(name):
            os.unlink(name)


def change_app(name, key, value):
    if not name or len(name) > 512 or key not in ('popups', 'sound') or value not in ('on', 'off'):
        raise Plain('choose an app, pop-ups or sound, and on or off')
    SETTINGS.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    if SETTINGS.parent.is_symlink():
        raise Plain('the settings folder is a link')
    fd = os.open(SETTINGS.parent / '.notifications.lock', os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, 'w') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        saved = read()
        apps = dict(saved.get('apps') or {})
        apps[name] = dict(apps.get(name) or {}, **{key: value == 'on'})
        saved['apps'] = apps
        explain({k:saved.get(k,v) for k,v in DEFAULTS.items()})
        schema.payload('notifications', {k:saved.get(k,v) for k,v in DEFAULTS.items()})
        write_saved(saved)


def main(args):
    if args == ["help"] or any(a in ("-h", "--help") for a in args):
        print(__doc__)
        return 0
    if len(args) == 4 and args[0] == "set-app":
        try:
            change_app(*args[1:])
            print(json.dumps({"ok": True}))
            return 0
        except (OSError, ValueError, TypeError) as error:
            print("Couldn't save the app's notification setting.", file=sys.stderr)
            return 1
    if args[:1] == ["apply"] and args != ["apply", "--stdin"]:
        print("starchaser notifications: apply reads the settings from standard input. "
              "Run: starchaser notifications apply --stdin < settings.json", file=sys.stderr)
        return 2
    if args[:1] == ["export"] and args != ["export"]:
        print("starchaser notifications: export takes no extra words. "
              "Run: starchaser notifications export", file=sys.stderr)
        return 2
    if args not in (["export"], ["apply", "--stdin"]):
        reason = f"unknown command {' '.join(args)!r}" if args else "missing command"
        print(f"starchaser notifications: {reason}. "
              "Run 'starchaser notifications --help' for more help.", file=sys.stderr)
        print(__doc__, file=sys.stderr)
        return 2
    try:
        if args == ["export"]:
            result = export()
        else:
            try:
                value = schema.loads(sys.stdin.buffer.read(schema.MAX_BYTES + 1))
            except ValueError:
                raise Plain("the input isn't valid settings JSON") from None
            apply(value)
            result = {"ok": True}
        print(json.dumps(result, sort_keys=True))
        return 0
    except Plain as ex:
        text = str(ex)
        print("Notification settings were not saved: " + text + "." if args[0] == "apply"
              else "Notification settings could not be read: " + text + ".", file=sys.stderr)
        return 1
    except (OSError, TypeError, ValueError):
        print("Notification settings could not be read or saved.", file=sys.stderr)
        return 1


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