#!/bin/bash
SOURCE=~/cloud/euskera_hitzak.txt
ERRORS=~/cloud/euskera_errors.txt
if [[ "$1" == "errors" ]]
then
    SOURCE=~/cloud/euskera_errors.txt
fi
if [[ "$1" == "all" ]]
then
    SOURCE=~/cloud/euskera_all.txt
fi

line="x"

RED='\033[0;31m'
GREEN='\033[0;32m'
BOLD='\033[1m' # BOLD
NC='\033[0m' # No Color

echo ""
echo ""
echo "Enter the translation for the following words:"

FAILED=()
LEARNED=()

while [[ true ]]
do

    MAX=${#FAILED[@]};
    RAND=$(($RANDOM%4))

    LINE=""
    if [[ "$RAND" == "0" ]] && [[ $MAX > 0 ]]
    then
        IDX=$(($RANDOM%$MAX))
        SEARCH=${FAILED[$IDX]}
        if [[ "$SEARCH" != "" ]]
        then
            LINE=$(grep "$SEARCH"  $SOURCE)
        fi
    fi

    # Normal run
    if [[ "$LINE" == "" ]]
    then
        LINE=$(egrep '.' $SOURCE |sort -R|head -n 1)
    fi

    EUS=$(echo $LINE|cut -d':' -f 1|perl -pe 's/(^ | $)//g;')
    GAS=$(echo $LINE|cut -d':' -f 2|perl -pe 's/(^ | $)//g;')

    RAND=$(($RANDOM%4))

    FROM=""
    GUESS=""
    PROP=""

    if [[ "$RAND" == "0" ]]
    then
        FROM="[eus]"
        DISPLAY=$EUS
        GUESS=$GAS
    else
        FROM="[es]"
        DISPLAY=$GAS
        GUESS=$EUS
    fi

    if [[ " ${LEARNED[*]} " =~ " $DISPLAY " ]]; then
        echo "already learned - $DISPLAY!" > /dev/null
    else
        echo -en "${BOLD}$DISPLAY${NC} $FROM - Proposition: "
        read line
        if [[ "$GUESS" != "$line" ]]
        then
            echo -e "${RED}NO!${NC}: ${GREEN}$GUESS${NC}"
            FAILED+=("$GUESS")
        else
            LEARNED+=("$DISPLAY")
            #LEARNED+=("$GUESS")
            for i in "${!FAILED[@]}"; do
                if [[ ${FAILED[i]} = $GUESS ]]; then
                    echo "Remove word from FAILED list..."
                    unset 'FAILED[i]'
                fi
            done

        fi
    fi

done

