#! /bin/bash

argc=$#
argv=("$@")
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# source echo2ui util
. ${__dir}/echo2ui_utils --source-only

# check if arg is num
is_num()
 {
   re='^[0-9]+$'
   if ! [[ $1 =~ $re ]] ;
   then
       echo -e "\nError: provided argument $1 is not a valid integer \n" 
       display_usage
       exit 1
   fi
 }

display_usage()
 { 
   bordered_title "echo2ui by keshavnrj@gmail.com"
   echo -e "\necho2ui shows informational messages using xterm and whiptail\n" 
   echo -e "\nUsage: $0 [context name] [title] [message] [width] [height]\n" 
   echo -e "Example: $0 'My Context' 'My Title' 'Hello from echo2ui!' 60 20\n"
 }
 
# check whether user had supplied -h or --help . If yes display usage 
 if [[ ( $* == "--help") ||  $* == "-h" ]] 
 then 
   display_usage
   exit 0
 fi 
 
# if less than 5 arguments supplied, display usage 
 if [[ $* != "--help" || $* != "-h" ]] && [ $# -le 4 ]; 
 then 
   echo -e "\nError: insufficient arguments passed \n" 
   display_usage
   exit 1
 else
  for (( k=3; k<argc; k++ )); do
    is_num "${argv[k]}"
  done
 fi 
 

# bootstap
 : ${PROG=xterm} 
 : ${AGENT=whiptail}

 export NEWT_COLORS='
   root=,black
 '
 if [ "$PROG" == "xterm" ]; then
   TERM='xterm-256color'
 else
   TERM='st-256color'
 fi

 CONTEXT=$1
 
 # change unset geometry if $4 & &5 are 0
  if [[ "$4" -eq "0" || "$5" -eq "0" ]];
  then
    PROG_GEOMETRY="62x20+0+0"
    AGENT_SIZE="20 62"
  else
    PROG_GEOMETRY="${4}x${5}+0+0"
    AGENT_SIZE="${5} ${4}"
  fi
  
  echo $PROG;
 
 if [ "$PROG" == "xterm" ]; then
   $PROG -fa "-misc-fixed-medium-r-normal--20-200-75-75-c-100-iso8859-1" -fs "10" -title "${CONTEXT}" -geometry "${PROG_GEOMETRY}" -e bash -c "$AGENT --ok-button 'Close' ${scrolltext} --title "\""${CONTEXT^^}: ${2}"\"" --msgbox "\""${3}"\"" ${AGENT_SIZE}"
 else
   $PROG -f "DejaVu Sans Mono:size=12" -T "${CONTEXT}" -g "${PROG_GEOMETRY}" -e bash -c "$AGENT --ok-button 'Close' ${scrolltext} --title "\""${CONTEXT^^}: ${2}"\"" --msgbox "\""${3}"\"" ${AGENT_SIZE}"
 fi
