#!/bin/bash

# Fuzzy find images with a preview.

dep_check () {
	for dep; do
		if ! command -v "$dep" 1>/dev/null; then
			printf "%s is not installed\n" "$dep" >&2
			exit
		fi
	done
	unset dep
}
dep_check "fzf" "chafa"

options="--color=always --type f"
FZF_DEFAULT_COMMAND="LS_COLORS=$LS_COLORS:'di=0;34' fdfind $options \
						    -e jpg -e png | shuf"

if [ $# -eq 0 ]; then
    # Find images in the current directory
    fzf --preview "chafa -f sixel -s 46x31 {}" \
		      --ansi --bind 'ctrl-m:execute:(openwith {})'
else
    while [ ! $# -eq 0 ]; do
	case "$1" in
	    --shuffle | -s)
		# Randomize file list
		fdfind -0  | xargs -0 feh -Tss
		;;
	    --default | -d)
		# Find images in the Pictures folder.
		cd ~/Pictures || exit
                # https://github.com/junegunn/fzf/blob/master/bin/fzf-preview.sh
                # FIXME: dimensions should change dynamically. The
                # following doesn't work: stty size < /dev/tty | awk
                # '{print $2 "x" $1}'
		fzf --preview "chafa -f sixel -s 46x31 {}" \
		    --ansi --bind 'ctrl-m:execute:(openwith {})'
		;;
	esac
	shift
    done
fi

