#!/bin/bash

# Fuzzy find video files with a preview

# - https://github.com/seebye/ueberzug
# - https://github.com/gokcehan/lf/wiki/Previews
# - https://github.com/cirala/vifmimg/blob/master/vifmimg

cd ~/Pictures || exit

filter="-e .mp4 -e .mov -e .avi -e .ogg -e .ogv"
FZF_DEFAULT_COMMAND="LS_COLORS=$LS_COLORS:'di=0;34' fdfind $filter --color=always --type f | shuf"

# Function to generate a thumbnail hash
thumb_hash() {
    local file="$1"
    local stat_info=$(stat --printf '%n\0%i\0%F\0%s\0%W\0%Y' -- "$(readlink -f "$file")")
    echo "$HOME/.cache/video-thumbnails/$(echo -n "$stat_info" | sha256sum | awk '{print $1}').jpg"
}

draw_preview() {
    local file="$1"
    local cache="$(thumb_hash "$file")"

    if ! [ -f "$cache" ]; then
	ffmpegthumbnailer -i "$PWD/$file" -o "$cache" -s 0 -q 5
    fi

    local -A add_preview_command=( \
				   [identifier]="images" \
                                   [scaler]=contain [scaling_position_x]=0.5 [scaling_position_y]=0.5 \
				   [path]="$cache")

    function adjust_rect {
        local -n placement_rect="$1"
        ((placement_rect[y]+=0))
        ((placement_rect[x]+=0))
    }
    ADD_PLACEMENT add_preview_command adjust_rect
}

export -f draw_preview
export -f thumb_hash

if [ $# -eq 0 ]; then
    fzf-ueberzogen.sh --ansi --exact --print-query -0 -1 \
		      --bind "ctrl-m:execute-silent:(mpv {+})" \
		      --preview 'draw_preview {}' \
		      --preview-window "right"
else
    while [ ! $# -eq 0 ]; do
	case "$1" in
	    --autoplay | -a)
		# Auto play files randomly
		fdfind -0 "$filter" | xargs -0 mpv --shuffle
		;;
	esac
	shift
    done
fi

