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


def readfile(path):
    fd = open(path, "r")
    result = fd.read()
    fd.close()
    return result

vals = {}
home = os.environ["HOME"]
appsdir=["/usr/share/applications", f"{home}/.local/share/applications"]
for appdir in appsdir:
    if not os.path.isdir(appdir):
        continue

    for appfile in os.listdir(appdir):
        if not appfile.endswith(".desktop"):
            continue

        path = appdir + "/" + appfile
        content = readfile(path)

        _name = None
        _exec = None
        _type = None
        _nodisplay = ""
        _hidden = ""
        for line in content.splitlines(content):
            line = line.strip()

            if line.startswith("Exec="):
                _exec = line[5:]
            elif line.startswith("Type="):
                _type = line[5:]
            elif line.startswith("Name="):
                _name = line[5:]
            elif line.startswith("NoDisplay="):
                _nodisplay = line[10:]
            elif line.startswith("Hidden="):
                _hidden = line[7:]


        if _name is None or _exec is None:
            continue
        if _type is None or _type != "Application":
            continue
        if _nodisplay == "true" or _hidden == "true":
            continue

        vals[_name] = {"kind": "app", "exec": _exec, "path": path}


bindir = f"{home}/bin"
for file in os.listdir(bindir):
    path = f"{bindir}/{file}"
    if os.path.isdir(path):
        continue
    if file.startswith("."):
        continue
    vals[file] = {"kind": "bin", "path": path}

def walk_bookmarks(node, folder=""):
    if isinstance(node, dict):
        if node.get("type") == "url" and node.get("url"):
            name = node.get("name") or node["url"]
            label = f"{folder}/{name}" if folder else name
            vals[label] = {"kind": "url", "url": node["url"]}
        elif "children" in node:
            name = node.get("name", "")
            next_folder = f"{folder}/{name}" if folder and name else name or folder
            for child in node.get("children", []):
                walk_bookmarks(child, next_folder)

bookmarkfile = f"{home}/.config/chromium/Default/Bookmarks"
if os.path.isfile(bookmarkfile):
    content = readfile(bookmarkfile)
    data = json.loads(content)

    roots = data.get("roots", {})
    for root in roots.values():
        walk_bookmarks(root)

entries = []
for it in vals.items():
    entries.append(it[0])
entries_string = "\n".join(entries)
result = subprocess.run(["wmenu", "-l", "20", "-i"], input=entries_string, text=True, stdout=subprocess.PIPE)

if result.returncode != 0:
    exit(result.returncode)

choice = result.stdout.strip()
val = vals[choice]


if val["kind"] == "bin":
    subprocess.run([val["path"]])
elif val["kind"] == "app":
    subprocess.run(["gtk-launch", choice])
elif val["kind"] == "url":
    subprocess.run(["xdg-open", val["url"]])
