#!/bin/sh

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

X="$2"
Y="$3"
WIDTH="$4"
HEIGHT="$5"
TMP="$HOME/.cache/vifm/thumbnail.$(stat --printf '%n\0%i\0%F\0%s\0%W\0%Y' -- "$(readlink -f "$1")" | sha256sum | awk '{print $1}')"

_preview_video() {
  [ ! -f "${TMP}.jpg" ] && ffmpegthumbnailer -i "$1" -o "${TMP}.jpg" -s 0
  kitty icat --silent --place=${WIDTH}x${HEIGHT}@${X}x${Y} "${TMP}.jpg"
}

_preview_image() {
  [ ! -f "${TMP}.jpg" ] && convert "$1"'[0]' "${TMP}.jpg"
  kitty icat --silent --place=${WIDTH}x${HEIGHT}@${X}x${Y} "${TMP}.jpg"
}

case "$1" in
  # First check common extensions
  *.png|*.jpg|*.bmp|*.jpeg|*.gif|*.xpm) kitty icat --silent --place=${WIDTH}x${HEIGHT}@${X}x${Y} "$1" ;;
  *.avi|*.mp4|*.wmv|*.dat|*.3gp|*.vob|*.ogv|*.mkv|*.mpe?g|*.fl[icv]|*.m2v|*.webm|*.m?ts|*.r[am]|*.qt|*.divx|*.as[fx]|*.m4v|*.mov) _preview_video "$1" ;;
  # Then fallback to mimetypes
  *)
    mimetype=$(file --dereference --brief --mime-type -- "$1")
    case "$mimetype" in
      image/vnd.djvu)
        djvutxt "$1" || exiftool "$1" ;;
      image/*)
        _preview_image "$1" ;;
      application/font*|application/*opentype|font/*)
        [ ! -f "${TMP}.jpg" ] && genfontimage "$1" "${TMP}.jpg"
        kitty icat --silent --place=${WIDTH}x${HEIGHT}@${X}x${Y} "${TMP}.jpg" ;;
      video/*)
        _preview_video "$1" ;;
      *)
        exit 1 ;;
    esac ;;
esac
