#!/run/current-system/sw/bin/bash

[ -d "$HOME/.cache/vifm" ] || mkdir -p "$HOME/.cache/vifm"

# $1 action
action="$1"
# $2 panel width
# $3 panel height
panel_width=$2
panel_height=$3
cell_width=10
cell_height=18
width=$((panel_width*cell_width))
height=$((panel_height*cell_height))
# $4 image path
image_file="$4"
background=black

PCACHE="$HOME/.cache/vifm/thumbnail.$(stat --printf '%n\0%i\0%F\0%s\0%W\0%Y' -- "$(readlink -f "$PWD/$image_file")" | sha256sum | awk '{print $1}')"

cleanup() {
		printf '\33[s\33[5A\33[2K\33[u'
		clear
		exit 0
}

case "$action" in
	"clear")
		cleanup
		;;
	"draw")
	img2sixel -S --width=$width $image_file
		;;
	"video")
		[ ! -f "${PCACHE}.jpg" ] && \
		ffmpegthumbnailer -i "$4" -o "${PCACHE}.jpg" -s 0 -q 5
	img2sixel --width=$width ${PCACHE}.jpg
		;;
	"epub")
		[ ! -f "${PCACHE}.jpg" ] && \
		epub-thumbnailer "$image_file" "$PCACHE" 1024
	img2sixel --width=$width --height=$height ${PCACHE}.jpg
		;;
	"pdf")
		[ ! -f "${PCACHE}.jpg" ] && \
		pdftoppm -jpeg -f 1 -singlefile "$image_file" "$PCACHE"
	img2sixel --height=$height ${PCACHE}.jpg
		;;
	"font")
		[ ! -f "${PCACHE}.jpg" ] && \
		fontpreview -i "$image_file" -o "${PCACHE}.jpg"
	img2sixel --width=$width --height=$height ${PCACHE}.jpg
		;;
	*)
esac