#!/usr/bin/python3
import json
import subprocess
import os
import sys

tag = str(sys.argv[1])
cmd = sys.argv[2]

if "WAYLAND_DISPLAY" in os.environ:
    msgcmd = "swaymsg"
else:
    msgcmd = 'i3-msg'


def get_workspace(nodes):
    for node in nodes:
        if node["type"] == "workspace" and node["name"] == tag:
            return node
        possiblenode = get_workspace(node.get("nodes", []))
        if possiblenode:
            return possiblenode


proc = subprocess.Popen([msgcmd, '-t', 'get_tree'], stdout=subprocess.PIPE)
root = json.load(proc.stdout)
workspace = get_workspace(root["nodes"])
if workspace and workspace["nodes"]:
    subprocess.Popen([msgcmd, 'workspace', tag])
    sys.exit(0)

subprocess.Popen([msgcmd, 'workspace', tag])
os.execlp(cmd.split()[0], *cmd.split())
