#!/usr/bin/env python3
"""Show or tune panel-bar label sizes.

    panel-bar-size                    show current values
    panel-bar-size 28                 FONT_SIZE for every label, px
    panel-bar-size word 32            per instance: word | weather | clocks | music
    panel-bar-size box 1.2            BOX (taller box = smaller text on screen)
    panel-bar-size height L [--restart]
                                      size of the extra panel (XS S M L XL Custom(N))

Label settings are written to ~/.config/cosmic-tools/panel-bar.conf and take
effect at each plugin's next refresh. A panel height change is written to the
COSMIC panel config (after a backup) and needs a panel restart: pass --restart,
or log out and in again.

Why sizes work this way: cbar scales every label image to a fixed height, so the
visible text size depends on how much of the image the glyphs fill. The labels
are drawn as SVG at FONT_SIZE px inside a box of FONT_SIZE x BOX px.
"""

import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
for cand in (os.environ.get("COSMIC_TOOLS_PANEL_SHARE", ""),
             os.path.join(HERE, ".."),
             os.path.expanduser("~/.local/share/cosmic-tools/panel-bar")):
    if cand and os.path.isfile(os.path.join(cand, "lib", "ctconfig.py")):
        sys.path.insert(0, os.path.join(cand, "lib"))
        break
import ctconfig     # noqa: E402
import cosmicpanel  # noqa: E402

INSTANCES = ("word", "weather", "clocks", "music")


def set_key(key, value):
    path = ctconfig.conf_path()
    try:
        with open(path, encoding="utf-8") as fh:
            lines = fh.read().splitlines()
    except OSError:
        lines = []
    pat = re.compile(r"^\s*(export\s+)?%s=" % re.escape(key))
    new = "%s=%s" % (key, value)
    for i, line in enumerate(lines):
        if pat.match(line):
            lines[i] = new
            break
    else:
        lines.append(new)
    cosmicpanel.write_atomic(path, "\n".join(lines) + "\n")
    print("%s -> %s" % (new, path))


def number(text):
    try:
        v = float(text)
    except ValueError:
        sys.exit("not a number: %s" % text)
    if v <= 0:
        sys.exit("must be positive: %s" % text)
    return text


def show():
    ctconfig._cache.clear()
    size = ctconfig.get("FONT_SIZE", "26")
    print("FONT_SIZE    : %s px" % size)
    for inst in INSTANCES:
        key = "FONT_SIZE_%s" % inst.upper()
        print("%-13s: %s" % (key, ctconfig.get(key, "(= FONT_SIZE)")))
    print("BOX          : %s" % ctconfig.get("BOX", "1.0"))
    print("BOX_PLAYING  : %s" % ctconfig.get("BOX_PLAYING", "1.35"))
    name = ctconfig.get("PANEL_NAME", "WordBar")
    try:
        with open(os.path.join(cosmicpanel.panel_dir(name), "size")) as fh:
            height = fh.read().strip()
    except OSError:
        height = "(no panel named %s)" % name
    print("panel height : %s" % height)


def main(argv):
    restart = "--restart" in argv
    argv = [a for a in argv if a != "--restart"]
    if not argv:
        show()
        return 0
    if argv[0] in ("-h", "--help"):
        print(__doc__)
        return 0
    if argv[0] in INSTANCES and len(argv) == 2:
        set_key("FONT_SIZE_%s" % argv[0].upper(), number(argv[1]))
    elif argv[0] in ("box", "box-playing") and len(argv) == 2:
        set_key("BOX" if argv[0] == "box" else "BOX_PLAYING", number(argv[1]))
    elif argv[0] == "height" and len(argv) == 2:
        if not re.match(r"^(XS|S|M|L|XL|Custom\(\d+\))$", argv[1]):
            sys.exit("height must be XS, S, M, L, XL or Custom(N)")
        name = ctconfig.get("PANEL_NAME", "WordBar")
        path = os.path.join(cosmicpanel.panel_dir(name), "size")
        if not os.path.isdir(os.path.dirname(path)):
            sys.exit("no COSMIC panel named %s" % name)
        print("backup: %s" % cosmicpanel.backup("panel-size", [path]))
        cosmicpanel.write_atomic(path, argv[1])
        if restart:
            cosmicpanel.restart_panel()
        else:
            print("restart the panel (--restart) or log out for the height to apply")
    elif len(argv) == 1:
        set_key("FONT_SIZE", number(argv[0]))
    else:
        print(__doc__)
        return 2
    return 0


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