#!/usr/bin/env bash
# Change_Installed_exe function
# Finds exe installed in drive_c by an installer
# and set the variable SELECTED_EXE
# FIXME change this to list installed exe function to be used by Open Other EXE and Change EXE
script-get-selected-exe()
{
  dbug "I: Script: Launched ${FUNCNAME[0]}"
  
  SOURCE "script-check-variables-loaded-or-not"
  script-check-variables-loaded-or-not
  unset COMMAND count SHOW_OPTION NAMES FILES RESULT search_list

  count=0
  NAMES=()
  FILES=()

  # Find all exe files in drive_c Exclude windows directory,
  # and common exe files present in Program Files directory
  # Add those files to FILES array and filenames to NAMES array
  SOURCE "script-get-installed-exe-files"
  script-get-installed-exe-files
  EXE_LIST="${EXE_FILES_FOUND}"
  search_list=$(echo "${EXE_LIST}"|tr "\n" "|")

  exe_found=$(echo ${search_list}|grep -i "exe")
 
  if [ -z "${exe_found}" ] ; then
       ${ZENITY_CMD} --error --title "${PROGNAME} - no exe installed!" \
              --text "Sorry, no exe found in prefix: \"${PREFIXNAME}\""
       Script_Window
  fi

  SAVEIFS=${IFS}
  IFS=$(echo -en "\n\b")

  # if exe_found has value, then only change exe
  for i in $(echo ${search_list}|tr '|' '\n'|sort)
  do
      RealName=$(basename "$i")
      RealFile=$(realpath -m "$i")
 
      # If 1st value is empty, enable it
      if [ -z "${SHOW_OPTION}" ]; then
           SHOW_OPTION+="TRUE \"${RealName}\""
           SHOW_OPTION+=" "
           NAMES+=("${RealName}")
           FILES+=("${RealFile}")
      else
           SHOW_OPTION+="0 \"${RealName}\""
           SHOW_OPTION+=" "
           NAMES+=("${RealName}")
           FILES+=("${RealFile}")
      fi
      count=$(expr ${count} + 1)
  done
  IFS=${SAVEIFS}
 
  # Generate Height value
  SOURCE "winezgui-get-window-height"
  winezgui-get-window-height ${#FILES[@]}
 
  # 3. Show the found exe files using zenity
  unset COMMAND
  COMMAND+="${ZENITY_CMD} --title=\"Exe inside ${PREFIXNAME}\" "
  COMMAND+="--radiolist --list --width=460 --height=${HEIGHT} "
  COMMAND+="--text=\"Select Exe...\" "
  COMMAND+="--hide-header --column \" \" --column \"Action\" ${SHOW_OPTION}"
  RESULT=$(eval ${COMMAND})
 
  if [ -z "${RESULT}" ]; then
       echo "Cancelled!"
       Script_Window
  fi
 
  count=0
  # 4. Find which file the user selected and set the selected exe into variable
  for i in "${NAMES[@]}"; do
      if [ "$i" = "$RESULT" ]; then
           echo "Selected $i"
           echo "File is ${FILES[${count}]}"
           export SELECTED_EXE="${FILES[${count}]}"
           export SELECTED_EXE_NAME=$(basename "${SELECTED_EXE}")
           break
      fi
      count=$(expr ${count} + 1)
  done
}
 
