#!/usr/bin/env python

"""
Utility to generate the workspace buttons for eww bar widget.

Currently it fetches information from monitor 0. If all monitors have
synchronised workspaces this should not be a problem.
"""
import os, sys, socket, json

WORKSPACE_ICONS = [
    (1, '☱'),
    (2, '☲'),
    (3, '☳'),
    (4, '☴'),
    (5, '☵'),
    (6, '☶'),
    (7, '☷'),
    (8, '☰'),
]
EXTRA_WORKSPACE_ICONS = [
    (0, '⚌'),
    (1, '⚍'),
    (2, '⚎'),
    (3, '⚏'),
]

def get_workspace_info():

    workspaces = json.loads(os.popen('hyprctl workspaces -j').read())
    monitors = json.loads(os.popen('hyprctl monitors -j').read())
    if not monitors:
        print("No monitor found!", file=sys.stderr)
        return []

    monitor, active = [(m['name'], m['activeWorkspace']['id'])
                       for m in monitors if m['id'] == 0][0]
    workspaces = [(w['id'], w['id'] == active)
                  for w in workspaces
                  if w['monitor'] == monitor]
    return workspaces


def get_widgets():
    # get all workspace keys
    workspaces = {k: v for k, v in get_workspace_info()}
    def get_class(k):
        key = workspaces.get(k, None)
        if key is None:
            return 'inactive'
        elif key:
            return 'focused'
        else:
            return 'active'

    buttons = [
        f'"id": "{k}", "text": "{icon}", "class": "{get_class(k)}"'
        for k, icon in WORKSPACE_ICONS
    ]
    buttons = ', '.join(['{' + b + '}' for b in buttons])
    return '[' + buttons + ']'


def listen():
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    KEY = 'HYPRLAND_INSTANCE_SIGNATURE'
    signature = os.environ.get(KEY, None)
    if signature is None:
        print("Hyprland variable uninitialised.", file=sys.stderr)
        return
    server_address = f"/tmp/hypr/{signature}/.socket2.sock"
    try:
        sock.connect(server_address)
    except:
        print(f"Could not connect to {server_address}", file=sys.stderr)
        raise

    # The flush here is very important since python by default buffers!
    print(get_widgets(), flush=True)
    while sock:
        data = sock.recv(1024)
        if b'workspace' in data:
            print(get_widgets(), flush=True)


listen()