#!/usr/bin/env bash

feedback_confirmation() {
  msg="$1"
  default_yes="${2:-true}"

  if ${default_yes}; then
    options="(Y|n)"
  else
    options="(y|N)"
  fi

  log_warn "${msg}"
  read -p "${options} " -n 1 -r </dev/tty
  reply="${REPLY}"

  if [ -z "${reply}" ]; then
    if ${default_yes}; then
      return 0
    else
      return 1
    fi
  fi

  echo
  if echo "${reply}" | grep -E '^[Yy]$' >/dev/null; then
    return 0
  else
    return 1
  fi
}

feedback_enter() {
  read -r -p "Press enter to continue"
}

feedback_text() {
  question="$1"
  printf "%s" "$1 " >&2
  read -r answer
  echo "${answer}"
}

feedback_select_option_fallback() {
  options="$1"
  question="$2"

  digits="$(printf "%s" "${options}" | wc -l | wc -m | xargs -I% echo "% - 1" | bc 2>/dev/null || echo 2)"
  echo "${options}" | awk "{printf(\"%${digits}d %s\n\", NR, \$0)}" >/dev/tty
  echo

  selection="$(feedback_text "${question}" <>/dev/tty)"

  index=1
  for option in ${options}; do
    if [ "${index}" = "${selection}" ]; then
      selection="${option}"
      break
    fi
    index=$((index + 1))
  done

  echo "${selection}"
}

feedback_select_option() {
  options="$(cat)"
  question="${1:-Select a number}"

  if has fzf; then
    height="$(echo "${options}" | wc -l)"
    height="$((height + 2))"
    echo "${options}" \
      | fzf-tmux \
        --height "${height}" \
        --cycle \
        --inline-info \
        --header "${question}" \
        --reverse
  else
    # shellcheck disable=SC2250
    feedback_select_option_fallback "${options}" "${question}" \
      | tail -n1
  fi
}
