#!/bin/bash
# shellcheck disable=SC1001
#ignore regex - sign occurence
trap "kill 0" SIGINT # Kill all spawned subprocesses on ctrl^c
LOCATION=$(dirname "$0")
source "$LOCATION"/../common_tools

LOREM="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
ARGUMENT_COUNT="$#"

check_text(){
  if [ -n "$1" ]
  then
    if ! [[ "$*" =~ [^a-zA-Z0-9\ \-\.\@] ]]; then
      TEXT=$1
    else
      echo "🤷‍ Only basic alphanumeric characters are supported!"
      exit 1
    fi
  else
      echo "🤷‍ No text to insert!"
      exit 1
  fi
}

escape_spaces(){
  ESCAPED_TEXT=$(echo "$1" | sed -e 's/ /\%s/g')
}

send_text(){
  escape_spaces "$1"
  android_get_device_sdk "$SELECTED_DEVICE"
  if (( SDK > 27 )); then
    # Insert only first character
    adb -s "$SELECTED_DEVICE" shell "input text '${ESCAPED_TEXT:0:1}'"
    # Afterwards the rest - workaround for API 28+ edittext char skip bug
    adb -s "$SELECTED_DEVICE" shell "input text '${ESCAPED_TEXT:1:${#ESCAPED_TEXT}}'"
  else
    adb -s "$SELECTED_DEVICE" shell "input text '$ESCAPED_TEXT'"
  fi
}

execute_by_arguments(){
  echo "📲 Sending text to $SELECTED_DEVICE..."
  # Handle arguments
  if [ "$1" == "-l" ];
  then
    send_text "$LOREM"
  elif [ "$ARGUMENT_COUNT" -gt 1 ];
  then
    for ARGUMENT in "$@"
    do
      send_text "$ARGUMENT"
      sleep 0.5
      if ! [ "$ARGUMENT" = "${*: -1}" ]; then #if not last argument, jump to next field
       adb -s "$SELECTED_DEVICE" shell input keyevent 61
      fi
    done
  else
    send_text "$TEXT"
  fi
}

execute_for_all(){
  check_for_update
  android_get_devices_auth_dump

  for DEVICE in $(adb devices | grep -v "List"  | awk '{print $1}')
  do
    (SELECTED_DEVICE=$DEVICE; execute_by_arguments "$@") & # Set var and start command in subshell
  done
  wait
}

check_text "$@"
if [[ "$1" == "-a" ]]; then
  execute_for_all "${@:2}" # All arguments starting from 2nd
else
  android_choose_device
  execute_by_arguments "$@"
fi
