#!/bin/bash

# Check if a directory argument is provided
if [ -z "$1" ]; then
  echo "Usage: $(basename "$0") <directory>"
  exit 1
fi

directory="$1"

# Function to select a random image from the directory and subdirectories
select_random_image() {
  # Find all image files in the directory and subdirectories
  # and select one randomly
  image=$(
    find "${directory}" \
      -type f \
      '(' \
      -iname "*.jpg" -o \
      -iname "*.png" -o \
      -iname "*.gif" -o \
      -iname "*.jpeg" \
      ')' | shuf -n 1
  )
  echo "${image}"
}

# Main loop
while true; do

  # Select a random image
  if [ -z "${image}" ] || [ "${input}" = "n" ]; then
    clear
    image=$(select_random_image)
    # Display the image using wezterm imgcat
    wezterm imgcat "${image}"
  fi

  # Wait for user input
  echo "Press 'i' for file info, 'v' to view again, 'n' for a new image, or 'q' to quit."
  read -r -s -n 1 input

  case "${input}" in
    i)
      # Display file information
      clear
      echo ""
      stat "${image}"
      ;;
    v)
      # Redisplay the same image
      echo ""
      wezterm imgcat "${image}"
      ;;
    n)
      # Select and display a new image
      echo ""
      image="" # Set image to empty to trigger selection of a new image
      ;;
    q)
      # Exit the script
      echo ""
      echo "Exiting..."
      break
      ;;
    *)
      echo ""
      echo "Invalid input, try again."
      ;;
  esac
done
