#!/usr/bin/env python3
import i3ipc
import os
import signal

PID_FILE = '/tmp/workspace-colors.pid'

COLORS = {
    '1': '#69C3FF',
    '2': '#FF69C3',
    '3': '#69FFC3',
    '4': '#C369FF',
    '5': '#FFC369',
}

# Kill any previous instance
try:
    old_pid = int(open(PID_FILE).read())
    os.kill(old_pid, signal.SIGTERM)
except (OSError, ValueError):
    pass

with open(PID_FILE, 'w') as f:
    f.write(str(os.getpid()))

def apply_color(conn, ws_name):
    color = COLORS.get(ws_name)
    if color:
        conn.command(f'client.focused {color} {color} {color} {color} {color}')

def on_workspace_focus(conn, event):
    apply_color(conn, event.current.name)

conn = i3ipc.Connection()

focused = next((w for w in conn.get_workspaces() if w.focused), None)
if focused:
    apply_color(conn, focused.name)

conn.on(i3ipc.Event.WORKSPACE_FOCUS, on_workspace_focus)
conn.main()
