#!/usr/bin/env bash
shopt -s nullglob
set -e
set -o pipefail

readonly PROGNAME="$(basename "${0}")"
readonly PROGDIR="$( cd "$( dirname "$( readlink -f "${BASH_SOURCE[0]}" )" )" && pwd )"

# shellcheck disable=SC1090
# shellcheck disable=SC1091
if [ -s "${PROGDIR}/lib/functions" ]; then
  source "${PROGDIR}/lib/functions"
else
  source '/usr/lib/splatmoji/functions'
fi

main() {
  parse_args "$@" || \
    if [[ $? -eq 255 ]]; then
      # Printing help and listing langs both return 255 as a signal to exit
      # here with success
      exit 0
    else
      exit 1
    fi

  # Get configuation
  local conffile
  conffile="$(get_config_file)"
  declare -A config
  get_config "${conffile}" config
  if [ -n "${VERBOSE}" ]; then
    echo 1>&2
    echo '# Config:' 1>&2
    for key in "${!config[@]}"; do echo "'${key}':" "'${config["${key}"]}'" 1>&2; done
  fi

  # Get list of data files
  # shellcheck disable=SC2034
  local datafiles_list=()
  collect_data_files "${DISABLE_EMOJI_DB}" "${DISABLE_EMOTICON_DB}" LANGUAGES CLI_DATA_FILES datafiles_list
  if [ -n "${VERBOSE}" ]; then
    echo 1>&2
    echo '# Data files specified via cli:' 1>&2
    echo "${CLI_DATA_FILES[*]-''}" 1>&2
    echo 1>&2
    echo '# Data files final list:' 1>&2
    echo "${datafiles_list[*]}" 1>&2
  fi

  # User selection
  local selection
  selection="$(get_user_selection SKIN_TONES_EXCLUDE datafiles_list "${config['rofi_command']}")"
  if [ -n "${VERBOSE}" ]; then
    echo 1>&2
    echo '# Un-escaped user selection:' 1>&2
    echo "'${selection}'" 1>&2
  fi
  # Remove prepended unicode left-to-right mark if present
  selection=${selection#$'\u200e'}
  if [ -n "${ESCAPE}" ]; then
    selection=$(escape_selection "${selection}" "${ESCAPE}")
    if [ -n "${VERBOSE}" ]; then
      echo 1>&2
      echo '# Escaped user selection:' 1>&2
      echo "'${selection}'" 1>&2
    fi
  fi

  if [ "${SUBCOMMAND}" == 'type' ]; then
    output_typed "${config[xdotool_command]}" "${selection}"
  else
    output_copied "${config[xsel_command]}" "${selection}"
  fi
}

main "$@"
