#!/bin/bash
#
mkdir -p $HOME/.trans_tray/{geometry,savedtexts,icons} 2> /dev/null
mkdir /tmp/trans_tray 2> /dev/null

export LANGUAGES='Afrikaans - af!Albanian - sq!Amharic - am!Arabic - ar!Armenian - hy!Azerbaijani - az!Basque - eu!Belarusian - be!Bengali - bn!Bosnian - bs!Bulgarian - bg!Cantonese - yue!Catalan - ca!Cebuano - ceb!Chichewa - ny!Chinese(Simple) - zh-CN!Chinese(Trad) - zh-TW!Corsican - co!Croatian - hr!Czech - cs!Danish - da!Dutch - nl!English - en!Esperanto - eo!Estonian - et!Fijian - fj!Filipino - tl!Finnish - fi!French - fr!Frisian - fy!Galician - gl!Georgian - ka!German - de!Greek - el!Gujarati - gu!Haitian-Creole - ht!Hausa - ha!Hawaiian - haw!Hebrew - he!Hindi - hi!Hmong - hmn!Hmong-Daw - mww!Hungarian - hu!Icelandic - is!Igbo - ig!Indonesian - id!Irish - ga!Italian - it!Japanese - ja!Javanese - jv!Kannada - kn!Kazakh - kk!Khmer - km!Klingon - tlh!Korean - ko!Kurdish - ku!Kyrgyz - ky!Lao - lo!Latin - la!Latvian - lv!Lithuanian - lt!Luxembourgish - lb!Macedonian - mk!Malagasy - mg!Malay - ms!Malayalam - ml!Maltese - mt!Maori - mi!Marathi - mr!Mongolian - mn!Myanmar - my!Nepali - ne!Norwegian - no!Pashto - ps!Persian - fa!Polish - pl!Portuguese - pt!Punjabi - pa!Queretaro-Otomi - otq!Roman - rm!Romanian - ro!Russian - ru!Samoan - sm!Scots-Gaelic - gd!Serbian(Cyr) - sr-Cyrl!Serbian(Latin) - sr-Latn!Sesotho - st!Shona - sn!Sindhi - sd!Sinhala - si!Slovak - sk!Slovenian - sl!Somali - so!Spanish - es!Sundanese - su!Swahili - sw!Swedish - sv!Tahitian - ty!Tajik - tg!Tamil - ta!Tatar - tt!Telugu - te!Thai - th!Tongan - to!Turkish - tr!Udmurt - udm!Ukrainian - uk!Urdu - ur!Uzbek - uz!Vietnamese - vi!Welsh - cy!Xhosa - xh!Yiddish - yi!Yoruba - yo!Yucatec-Maya - yua!Zulu - zu'

export run_cmd='@bash -c "run_trans %1 %2 %3 %4"'

[ -f  $HOME/.trans_tray/prefs ] && . $HOME/.trans_tray/prefs
[ "$ON_TOP" = "TRUE" ] && export ONTOP="--on-top"

export fpipe="/tmp/trans_tray/run_trans.$RANDOM"
mkfifo "$fpipe"
export dpipe="/tmp/trans_tray/switch_trans.$RANDOM"
mkfifo "$dpipe"

trap "rm -f $fpipe $dpipe" EXIT

fkey=$(($RANDOM * $$))

function run_trans_save {
. $HOME/.trans_tray/prefs
[ "$ON_TOP" = "TRUE" ] && ONTOP="--on-top"
[ ! -f /tmp/trans_tray/r_trans ] && exit
DATE=$(date +"%Y%m%d_%H%M%S")
cp -a /tmp/trans_tray/r_trans  $HOME/.trans_tray/savedtexts/trans-$DATE
[[ -e "/tmp/trans_tray/TP" && -e "/tmp/trans_tray/PT" ]] && refresh
yad --title="Translation saved" --borders=6 --window-icon=$ICON --text="  <b>Saved to ~/.trans_tray/savedtexts/trans-$DATE </b>" --geometry=500x35-40-70 --undecorated --timeout 4 --no-buttons $ONTOP
}
export -f run_trans_save

function run_trans
{
    echo "3:@disable@"
export TLANG="$1"
export _TLANG=$(echo "$1" | awk '{print $1}')
echo $TLANG > $HOME/.trans_tray/.trans_target_lang1
[ -z "$TLANG" ] && export TLANG="English - en"
[ -z "$_TLANG" ] && export _TLANG="English"
export ENGINE=$(cat $HOME/.trans_tray/_trans_engine_2 2> /dev/null)
[ -z "$ENGINE" ] && ENGINE=google
  echo -e '\f' >> "$fpipe"
[ -n "$2" ] && export TTEXT="$2" || exit
#echo "Using $ENGINE for translating"

for ex in $ENGINE
do
#echo "icon:/tmp/$ex.svg" >$PIPE
echo "----- $ex translate to $(echo $TLANG | awk '{print $1}') -----"
echo -e "$TTEXT" | trans -e $ex -b -tl $(echo $TLANG | awk '{print $NF}'); done | tee /tmp/trans_tray/r_trans >> "$fpipe"
echo "3:$run_cmd"
}
export -f run_trans

export run_cmnd='@bash -c "switch_lang %1 %2 %3 %4"'

switch_lang () {
    echo "4:@disable@"
[ -n "$2" ] && export TTEXT="$2" || exit

SRC=$(echo "$TTEXT" | trans -identify -no-ansi)

# try bing if default google gives empty $SRC 
[ -z "$SRC" ] && SRC=$(echo "$TTEXT" | trans -e bing -identify -no-ansi)
SRCNAME=$(echo "$SRC" | grep -m 1 "Name" 2> /dev/null | awk '{print $2}')
[ -z "$SRCNAME" ] && exit
    echo -e "\f" > $dpipe
SRCCODE=$(echo "$SRC" | grep -m 1 "Code" | awk '{print $2}')
    echo -e "$SRCNAME - $SRCCODE!$LANGUAGES" >> $dpipe
    echo "$SRCNAME - $SRCCODE" > $HOME/.trans_tray/.trans_target_lang1

#if [ "$(xclip -o)" ]; then
if [ -f /tmp/trans_tray/r_trans ]; then
#tt=$(while read -r line; do printf "%s" "$line\n"; done <<< "$(xclip -o)")
tt=$(while read -r line; do printf "%s" "$line\n"; done <<< "$(cat /tmp/trans_tray/r_trans | grep -v " -----")")

printf "%s\n" "$tt"  >> "$dpipe"
else
echo -e "$TTEXT"  >> "$dpipe"
fi

   echo "$run_cmd" >> $dpipe
   echo "$run_cmnd" >> $dpipe
export TLANG=$(cat $HOME/.trans_tray/.trans_target_lang1 2> /dev/null)
export _TLANG=$(cat $HOME/.trans_tray/.trans_target_lang1 2> /dev/null | awk '{print $1}')

[ -z "$TLANG" ] && export TLANG="English - en"
echo $TLANG > $HOME/.trans_tray/.trans_target_lang1
[ -z "$_TLANG" ] && export _TLANG="English"
export ENGINE=$(cat $HOME/.trans_tray/_trans_engine_2 2> /dev/null)
[ -z "$ENGINE" ] && ENGINE=google
  echo -e '\f' >> "$fpipe"
[ -n "$2" ] && export TTEXT="$2" || exit
#echo "Using $ENGINE for translating"

for ex in $ENGINE
do
#echo "icon:/tmp/$ex.svg" >$PIPE
while read i; do
echo "----- $ex translate to $(echo $i | awk '{print $1}') -----"
echo -e "$TTEXT" | trans -e $ex -b -tl $(echo $i | awk '{print $NF}')
done <<< "$TLANG"; done | tee /tmp/trans_tray/r_trans >> "$fpipe"
    echo "4:$run_cmnd"

}
export -f switch_lang

function screenshotfn {
   # -vf scale=600:-1 
   DATE=$(date +"%Y%m%d_%H%M%S")
   IFS='+' read -r O P Q <<<"$(xrectsel)";sleep 0.2;ffmpeg -y -t 00:00:01 -f x11grab -re -video_size "$O" -i :0.0+"$P","$Q" /root/strans-"$DATE".png
   PIC=$(file /root/strans-"$DATE".png)
   IFS=':|,' read -r type o g h e f<<<$PIC
   size=$(echo  $g | tr -d ' ')
   yad --picture --undecorated --size=fit --filename=/root/strans-"$DATE".png --no-buttons --geometry="$size" &
};export -f screenshotfn


clear_all () {
echo -e '\f' > $fpipe
   echo -e "\f"  >> $dpipe
TLANG=$(cat $HOME/.trans_tray/.trans_target_lang1 2> /dev/null)
[ -z "$TLANG" ] && export TLANG="English - en"
   echo -e "$TLANG!$LANGUAGES"  >> $dpipe
echo -e ""  >> $dpipe
   echo "$run_cmd" >> $dpipe
   echo "$run_cmnd" >> $dpipe
}; export -f clear_all


exec 7<> $dpipe
exec 5<> $fpipe

export TLANG=$(cat $HOME/.trans_tray/.trans_target_lang1 2> /dev/null)
export _TLANG=$(cat $HOME/.trans_tray/.trans_target_lang1 2> /dev/null | awk '{print $1}')
[ -z "$TLANG" ] && export TLANG="English - en"
[ -z "$_TLANG" ] && export _TLANG="English"

   echo -e "\f"  >&7
   echo -e "$TLANG!$LANGUAGES"  >&7
if [ "$(xclip -o)" ]; then
   tt=$(while read -r line; do printf "%s" "$line\n"; done <<< "$(xclip -o)")
   printf "%s\n" "$tt"  >> "$dpipe"
else
echo -e ""  >> "$dpipe"
fi
   echo "$run_cmd" >&7
   echo "$run_cmnd" >&7

yad --plug="$fkey" --tabnum=1 --form --cycle-read  --field="Target language:CB" --field="Type some text to translate :TXT" --field="Translate!gtk-refresh:fbtn"  --field="Switch source <-> target!gtk-apply:fbtn" --no-markup <&7 &

yad --plug="$fkey" --tabnum=2 --text-info --editable --wrap --fore="black" --back="#FFF7EE" --margins=5 --file-op <&5 &

yad --center --paned --key="$fkey"  --button="Screenshot!!Selected Area Screencapture:bash -c screenshotfn" --buttons-layout=center --button="Clear All!!gtk-clear:bash -c clear_all" --button="Save!!gtk-save:bash -c run_trans_save" --button="Close!!gtk-close:1" --width=800 --height=600 \
--title="Translate" --window-icon="gtk-refresh" --splitter=350 --orient=hor $ONTOP
#rm -f /tmp/trans_tray/r_trans

