#!/bin/bash

# omarchy:summary=Pick a file with Walker
# omarchy:group=menu
# omarchy:name=file
# omarchy:args=label paths formats [walker args...]
# omarchy:examples=omarchy menu file "Select image" "$HOME/Pictures" "jpg png webp"|omarchy-menu-file "Select media" "$HOME/Pictures:$HOME/Videos" "jpg png mp4 mov" --width 800

set -euo pipefail

if (( $# < 3 )); then
  echo "Usage: omarchy-menu-file <label> <paths> <formats> [walker args...]" >&2
  exit 1
fi

label="$1"
paths_arg="$2"
formats_arg="$3"
shift 3

IFS=: read -r -a paths <<<"$paths_arg"
read -r -a formats <<<"$formats_arg"

if (( ${#paths[@]} == 0 || ${#formats[@]} == 0 )); then
  echo "Usage: omarchy-menu-file <label> <paths> <formats> [walker args...]" >&2
  exit 1
fi

for path in "${paths[@]}"; do
  [[ -e $path ]] || { echo "Path not found: $path" >&2; exit 1; }
done

find_args=("${paths[@]}" "(" -type d -name ".*" ! -name "." -prune ")" -o -type f ! -name ".*" "(")
first_format=true
for format in "${formats[@]}"; do
  if [[ $first_format == "true" ]]; then
    first_format=false
  else
    find_args+=(-o)
  fi

  format="${format#.}"
  find_args+=(-iname "*.$format")
done
find_args+=(")" -printf '%T@\t%p\n')

find "${find_args[@]}" 2>/dev/null | sort -rn | cut -f2- |
  omarchy-launch-walker --dmenu --width 800 --minheight 1 --maxheight 500 -p "$label…" "$@" 2>/dev/null
