#!/bin/bash
# info: list user notifications
# options: USER [FORMAT]
#
# The function for getting the list notifications


#----------------------------------------------------------#
#                    Variable&Function                     #
#----------------------------------------------------------#

# Argument definition
user=$1
format=${2-shell}

# Includes
source $VESTA/func/main.sh

# JSON list function
json_list() {
    IFS=$'\n'
    i=1
    objects=$(grep NID $USER_DATA/notifications.conf |wc -l)
    echo "{"
    while read str; do
        eval $str
        TOPIC=$(echo "$TOPIC" |sed -e "s/%quote%/'/g")
        NOTICE=$(echo "$NOTICE" |sed -e "s/%quote%/'/g")
        echo -n '    "'$NID'": {
        "TOPIC": "'$TOPIC'",
        "NOTICE": "'$NOTICE'",
        "TYPE": "'$TYPE'",
        "ACK": "'$ACK'",
        "TPL": "'$TPL'",
        "TIME": "'$TIME'",
        "DATE": "'$DATE'"
    }'
        if [ "$i" -lt "$objects" ]; then
            echo ','
        else
            echo
        fi
        ((i++))
    done < <(cat $USER_DATA/notifications.conf)
    echo '}'
}

# SHELL list function
shell_list() {
    IFS=$'\n'
    while read str; do
        eval $str
        echo "$TOPIC" |sed -e "s/%quote%/'/g"
        echo "$NOTICE" |sed -e "s/%quote%/'/g"
        echo "$DATE $TIME"
        echo "--"
        echo
    done < <(cat $USER_DATA/notifications.conf)
}

# PLAIN list function
plain_list() {
    IFS=$'\n'
    while read str; do
        eval $str
        TOPIC=$(echo "$TOPIC" |sed -e "s/%quote%/'/g")
        NOTICE=$(echo "$NOTICE" |sed -e "s/%quote%/'/g")
        echo -e "$NID\t$TOPIC\t$NOTICE\t$TIME\t$DATE"
    done < <(cat $USER_DATA/notifications.conf)
}

# CSV list function
csv_list() {
    IFS=$'\n'
    echo "NID,TOPIC,NOTICE,TIME,DATE"
    while read str; do
        eval $str
        TOPIC=$(echo "$TOPIC" |sed -e "s/%quote%/'/g")
        NOTICE=$(echo "$NOTICE" |sed -e "s/%quote%/'/g")
        echo "$NID,\"$TOPIC\",\"$NOTICE\",$TIME,$DATE"
    done < <(cat $USER_DATA/notifications.conf)
}


#----------------------------------------------------------#
#                    Verifications                         #
#----------------------------------------------------------#

# Checking args
check_args '1' "$#" 'USER [FORMAT]'
is_format_valid 'user'
is_object_valid 'user' 'USER' "$user"


#----------------------------------------------------------#
#                       Action                             #
#----------------------------------------------------------#

# Listing data
case $format in
    json)   json_list ;;
    plain)  plain_list ;;
    csv)    csv_list ;;
    shell)  shell_list ;;
esac


#----------------------------------------------------------#
#                       Vesta                              #
#----------------------------------------------------------#

exit