#!/usr/bin/env bash
#
# dependencies: chafa | imgcat | pdftoppm | ffmpegthumbnailer

if [ "$#" -ne 1 ]; then
  >&2 echo "Usage: $(basename "$0") <filename>"
  exit 1
fi

# file=${1/#\~\//$HOME/}
# file=$(echo "$1"| sed "s|${HOME}/||")
file="$1"

cleanup() {
  rm -f -- "${TMPDIR:-/tmp}"/preview.*
}
trap 'cleanup' EXIT

# function to preview text files
preview_text() {
  bat --style="${BAT_STYLE:-numbers,header}" --color=always --pager=never \
    --line-range :19 -- "${file}"
}

preview_json() {
  if command -v jq >/dev/null 2>&1; then
    jq --color-output . "${file}"
  elif command -v bat >/dev/null 2>&1; then
    bat --language=json --style=plain --color=always --paging=never -- "${file}"
  elif command -v python >/dev/null 2>&1; then
    python -m json.tool <"${file}"
  fi
}

preview_diff() {
  delta <"${file}"
}

preview_markdown() {
  if command -v glow >/dev/null 2>&1; then
    glow --style auto --width "${FZF_PREVIEW_COLUMNS:-}" -- "${file}"
  elif command -v bat >/dev/null 2>&1; then
    bat --language=markdown --color=always --paging=never -- "${file}"
  elif command -v pandoc >/dev/null 2>&1; then
    pandoc --standalone --from=gfm --to=man -- "${file}" | man --local-file -
  fi
}

# shellcheck disable=SC2154,SC2312
preview_image() {
  image_file="$1"

  if command -v kitty >/dev/null 2>&1 && test -n "${KITTY_WINDOW_ID}"; then
    dim=${FZF_PREVIEW_COLUMNS}x${FZF_PREVIEW_LINES}
    if [ "${dim}" = x ]; then
      dim=$(stty size </dev/tty | awk '{ print $2 "x" $1 }')
    elif ! test -n "${KITTY_WINDOW_ID}" && [ $((FZF_PREVIEW_TOP + FZF_PREVIEW_LINES)) = "$(stty size </dev/tty | awk '{ print $1 }')" ]; then
      dim=${FZF_PREVIEW_COLUMNS}x$((FZF_PREVIEW_LINES - 1))
    fi
    # shellcheck disable=SC3003
    kitty icat --clear --transfer-mode=memory --unicode-placeholder \
      --stdin=no --place="${dim}@0x0" -- "${image_file}" \
      | sed '$d' | sed $'$s/$/\e[m/'

  # elif command -v imgcat >/dev/null; then
  #   imgcat -W "${dim%%x*}" -H "${dim##*x}" -- "${image_file}"
  elif command -v chafa >/dev/null; then
    # chafa --format sixels -O 9 --work 1 --size "${dim}" "${image_file}"
    chafa --symbols all-braille-extra --animate off \
      --work 1 --scale 0.4 --clear -- "${image_file}"
    echo
  else
    file -L -- "${image_file}"
  fi
}

preview_pdf() {
  tmp_image=$(mktemp "${TMPDIR:-/tmp}"/preview.XXXXXX)
  # see pdftoppm(1) - preview first page only
  if pdftoppm -jpeg -f 1 -singlefile "${file}" "${tmp_image}" >/dev/null 2>&1; then
    tmp_image="${tmp_image}.jpg"
    preview_image "${tmp_image}"
  else
    file "${file}"
  fi
}

preview_audio() {
  if command -v exiftool >/dev/null; then
    exiftool -FileName -Title -Artist -Album -Genre -ChannelMode -AudioBitrate \
      -FileSize -MIMEType -SampleRate -Duration "${file}"
  else
    echo "exiftool not found."
    file "${file}"
  fi
}

preview_video() {
  tmp_image=$(mktemp "${TMPDIR:-/tmp}"/preview.XXXXXX.jpg)
  if ffmpegthumbnailer -i "${file}" -o "${tmp_image}" -s 0 >/dev/null 2>&1; then
    magick "${tmp_image}" -resize 25% "${tmp_image}"
    preview_image "${tmp_image}"
  else
    file "${file}"
  fi
}

preview_archive() {
  atool --list -- "${file}"
}

preview_dir() {
  echo
  (
    eza --grid --all --group-directories-first --color=always "${file}" \
      || tree -FC --charset=ascii -I '.git' -- "$1" \
      || find "${file}" -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
  ) 2>/dev/null
}

mime=$(file -L -i -- "${file}" | awk -F": " '{ print $2 }')
case "${mime}" in
  inode/directory*)
    preview_dir "${file}"
    ;;
  text/x-patch*)
    preview_diff "${file}"
    ;;
  text/x-diff*)
    preview_diff "${file}"
    ;;
  text/*)
    case "${file}" in
      *.md | *.markdown)
        preview_markdown "${file}"
        ;;
      *)
        preview_text "${file}"
        ;;
    esac
    ;;
  image/jpeg* | image/png*)
    preview_image "${file}"
    ;;
  application/json*)
    preview_json "${file}"
    ;;
  application/pdf*)
    preview_pdf "${file}"
    ;;
  audio/*)
    preview_audio "${file}"
    ;;
  video/*)
    preview_video "${file}"
    ;;
  application/zip* | application/x-tar* | application/gzip* | \
    application/x-bzip2* | application/x-xz* | application/x-rar* | \
    application/x-7z-compressed*)
    preview_archive "${file}"
    ;;
  *)
    file -L -i -- "${file}"
    # exiftool "${file}"
    ;;
esac
