#!/usr/bin/env bash

# Copyright 2021 Josh Holbrook
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

PYTHON="$(kbconfig get python path)"
DEBUG="${DEBUG:-}"

function log-debug {
  if [ ! -z "${DEBUG}" ]; then
    echo "debug:" "$@"
  fi
}

function log-info {
  echo "info:" "$@"
}

log-info "Grandmaw Korben's XDG Menu Explorer 🦜"
log-info '"nice work, pixel birdie!"'
log-info "programmed entirely while unemployed"
log-debug "it worked if it ends with ok"

if [[ "${OSTYPE}" == "darwin"* ]]; then
  APPLICATIONS==''
  DEPTH="$(./bin/kbconfig get menu depth)"

  IFS=: read -r -d '' -a APP_PATH < <(printf '%s:\0' "$(kbconfig get menu path)")

  for path in "${APP_PATH[@]}"; do
    if [ -n "${APPLICATIONS}" ]; then
      APPLICATIONS="${APPLICATIONS}
"
    fi
    APPLICATIONS="${APPLICATIONS}$(find "${path}" -iname '*.app' -maxdepth "${DEPTH:-2}")"
  done

  CHOICE="$(echo "${APPLICATIONS}" | fzf -m --preview "kbprev '{1}' '{2}' '{3}' '{4}' '{5}' '{6}' '{7}' '{8}'")"

  open -a "${CHOICE}"

  log-debug "ok"

  exit 0
fi

__PRELUDE='
import xdg.Menu


def __walk(path, node):
    path.append(node)

    if isinstance(node, xdg.Menu.Menu):
        for child in node.getEntries():
            yield from __walk(path, child)
    else:
        yield path[:]

    path.pop()


def __key(path):
    key = ""
    for node in path:
        key += "/"
        if isinstance(node, xdg.Menu.Menu):
            key += node.getName()
        else:
            key += node.DesktopEntry.getName()

    return key
'

__PREVIEW="${__PRELUDE}"'

for path in __walk([], xdg.Menu.parse()):
    print(__key(path))
'

__GET="${__PRELUDE}"'
import sys

COMMENTS = dict()

for path in __walk([], xdg.Menu.parse()):
    COMMENTS[__key(path)] = path[-1].DesktopEntry.getComment()

print(COMMENTS[" ".join([arg for arg in sys.argv[1:] if arg])])
'

__COMMAND="${__PRELUDE}"'
import re
import sys

FIELD_RE = r"(?<!%)(%\S)"
COMMANDS = dict()

for path in __walk([], xdg.Menu.parse()):
    COMMANDS[__key(path)] = re.sub(FIELD_RE, lambda m: "", path[-1].DesktopEntry.getExec())

print(COMMANDS[sys.argv[1]])
'

CHOICE="$("${PYTHON}" -c "${__PREVIEW}" | fzf -m --preview '"'"${PYTHON}"'"'" -c '${__GET}' '{1}' '{2}' '{3}' '{4}' '{5}' '{6}' '{7}' '{8}'")"

eval "nohup $("${PYTHON}" -c "${__COMMAND}" "${CHOICE}") &> /dev/null &"

log-debug "ok"
