#!/usr/bin/env bash
#
# fmusic - fuzzy find music with a preview

# shopt -s nullglob

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 "mpv" "fzf"

while [ "$#" -gt 0 ]; do
  # shellcheck disable=SC2249
  case "$1" in
    --music | -m)
      cd ~/Music || exit
      ;;
  esac
  shift
done

# preview

# fzf interface and options
options="--color=always --type f --exclude lyrics --exclude '*.png'"
# shellcheck disable=SC2034
FZF_DEFAULT_COMMAND="LS_COLORS=${LS_COLORS:-}:'di=0;34' fd ${options} \
| shuf"

query=$(
  fzf --ansi --exact --print-query --exit-0 --select-1 \
    --color='fg+:#edb443,fg:#949494,fg+:#949494,preview-bg:#000000,border:#0a3749' \
    --preview-window='top,23%' \
    --bind 'alt-a:select-all' \
    --bind 'alt-u:deselect-all' \
    --bind "alt-w:execute-silent(echo ${PWD}/{+} | wl-copy)" \
    --bind "alt-s:execute-silent(for i in {+}; do echo \"${PWD}/${i}\"; done | wl-copy)"
)

file=$(echo "${query}" | cut -d' ' -f1- | tail -1)
# https://github.com/junegunn/fzf/issues/1693
match=$(echo "${query}" | wc -l)

# 2+ matches means candidates were marked with TAB/C-i, so add those
# to the playlist
if [ "${match}" -gt 2 ]; then
  # IFS=$'\n'
  IFS=$(printf ' \n\t')
  playlist=$(for i in ${query}; do
    if [ -f "${i}" ]; then
      echo "${PWD}/${i}"
    fi
  done)
  mpv "${playlist}"
  unset IFS
else
  # 2 matches means one or more candidates were found
  # shellcheck disable=SC2312
  if [ "$(echo "${query}" | wc -l)" = 2 ]; then
    # Check the file type. Plain text means the file is a playlist
    # shellcheck disable=SC2312
    if [ "$(file --brief --mime-type "${file}")" = "text/plain" ]; then
      mpv --playlist="${file}"
    else
      dir=$(dirname "${PWD}/${file}")
      file=$(basename "${file}")
      cd "${dir}" || exit
      # array=(*)
      array="*"
      # shellcheck disable=SC2250
      eval "echo \"\$$array\""
      for i in ${array}; do
        if [ "${file}" = "${array}" ]; then
          mpv ./* --playlist-start="${i}"
        fi
      done
    fi
  else
    # 1 match means no match found so add a fallback. The fallback
    # works by typing "query" RET when no matches are found. If
    # matches *are* found, then we have to nullify the candidates
    # by typing a comma after the query. For example "query," or
    # "query, playlist".
    if [ -n "${file}" ]; then
      mpv --no-video --ytdl-format=worst ytdl://ytsearch10:"${file}"
    fi
  fi
fi
