#!/bin/sh

[ "$1" == "-h" ] && echo -e "deezersearch.sh [TYPE] [QUERY]\n[TYPE] is one of three: track, album, artist\n[QUERY] is the search term" && exit

#guicmd='fzf --no-info --height=6'

[ -z $1 ] && type=$(echo -e "track\nalbum\nplaylist" | $guicmd ) || type="$1"
[ -z $type ] && exit

[ -z "$2" ] && echo -n "Search: " && read query || query="$2"

query=$(xxd -p <<< "$query"| sed 's/../\%&/g')
echo $query
[ -z "$query" ] && exit

#curl -s "https://www.deezer.com/search/$query"
response="$(wget --no-hsts --no-check-certificate -e use_proxy=yes -O - https://www.deezer.com/search/$query -e https_proxy=136.228.220.138:8082)"
#wget --no-check-certificate -O - "https://www.deezer.com/search/$query"
#exit 0
#response="$(curl -s "https://www.deezer.com/search/$query")"

case $type in
        track)formated=$(echo "$response" | sed 's|{|\n|g' | grep "SNG_ID\":" | cut -d "," -f 1,4,7 | cut -d "\"" -f 4,8,12);;
        album)formated=$(echo "$response" | sed 's|},|\n|g'| grep "{\"ALB_ID\":" | cut -d "," -f 1,2,7 | sed 's|{|\n|g' | grep "ALB_ID" | cut -d "\"" -f 4,8,12);;
        playlist)formated=$(echo "$response" | sed 's|{|\n|g'| grep "\"PLAYLIST_ID\":" | cut -d "," -f 1,4 | cut -d "\"" -f 4,8 );;
esac

#choice=$(
#printf $formated
printf "$formated"| while read line
do
echo $(echo "$line"|cut -d '"' -f3) - $(echo "$line"|cut -d '"' -f2) deezer.com/en/$type/$(echo "$line"|cut -d '"' -f1)

done
#echo "$formated" | tr "\"" "-" | cut -d "-" -f 2,3| while read line;do echo $line deezer.com/en/$type/$(echo "$formated" | tr "\"" "-" | grep -Fwm1 "$line" | cut -d "-" -f 1);done

 #| $guicmd )
#[ -z "$choice" ] && exit

#echo "deezer.com/en/$type/$id"
