#!/bin/bash

Info () {
title="Info"
author="Peter Starfinger"
mail="E-Mail: info@die-starfingers.de"
year="2020"
app="$1"
msgid="The Starbuntu application
<i>\$app</i>
was written by"
info="$(gettext "$msgid" | (export PATH `envsubst --variables "$msgid"`; envsubst "$msgid"))"

yad --center --fixed --title="$title" --window-icon="info" --image="info" --borders=20 --text="$info"$'\n'$'\n'"$author"$'\n'"$mail"$'\n'$'\n'"$year"$'\n' --text-align=center --selectable-labels --button="OK" &
wunwa "$title" > /dev/null; xdotool key Home key Down
}

param="$1"
[ "$param" = "info" ] && Info "$2" && exit 0

h_file="$1"; leer=false
max=$2
text="$3"
if [ -z "$h_file" ]; then
    leer=true
    h_file="$HOME/.config/gtk-3.0/.history"
    pos="--center"
    entry_text=""
else
    pos="--mouse"
    entry_text="$(xsel -p)"
fi
lang_dir=$"C"
if [ -z "$text" ]; then
    [ $h_file = "$HOME/.config/gtk-3.0/.history" ] && text="$(echo $"Family member:")" && max=20 || text=$"Contents Of ""$(basename "$h_file":)"
fi
button1=$"Cancel"
button2=$"Help"

image="$4"

parent="$5"
if [ -z "$parent" ]; then parent="hist"; fi
IFS=$'\n'
hist=($(cat $h_file))

sh -c 'wunwa "$text" > /dev/null; xdotool key Home' &
if [ -n "$image" ]; then
    image_param1="--window-icon=$image"
    image_param2="--image=$image"
    image_param3="--image-on-top"
else
    image_param1=""
    image_param2=""
    image_param3=""
fi
[ -n "$entry_text" ] && xdotool sleep 0.5 type "$entry_text" &
item=`yad $pos --title="$text" --height=100 --width=350 --borders=10 --undecorated $image_param1 $image_param2 $image_param3 --list --editable --no-headers --column=History ${hist[@]} --text="<b>$text</b>" --entry-text="$entry_text" --entry --button="$button1":1 --button=$button2:"yelp /usr/share/help/$lang_dir/Starbuntu/starbuntu-apps-details.page#$(basename $parent)" --button="Info":"$0 info $(basename $parent)" --button="OK":0`

button="$?"

if [ $button -ne 252 ] && [ -n "$item" ]; then
    rm $h_file
    [ "${item::1}" = "-" ] && item=" $item"
    k=$(grep -nE "^$item$" <<< "${hist[*]}" | cut -d: -f1)
    [ $k -gt 0 ] && ((k--)) && unset "hist[$k]"
    hist=("$item" ${hist[@]})
    if [ ${#hist[@]} -gt $max ]; then
	unset "hist[((${#hist[@]}-1))]"
    fi
    echo "${hist[*]}" > $h_file
fi

unset IFS

if ! $leer; then
    echo "$item"
elif [ -n "$item" ]; then
    img="$HOME/.config/gtk-3.0/.Fotos/$item.jpg"
    /usr/bin/eog -f "$img"
fi
exit "$button"

