#!/usr/bin/env bash

# -----------------------------------------------------------------------------
# Info:
#   author:    Colin Powell
#   file:      rofi-radio.sh
#   created:   25.10.2020.-08:06:54
#   revision:  ---
#   version:   1.0
# -----------------------------------------------------------------------------
# Requirements:
#   rofi
# Description:
#   Use rofi to play radio stations
# Usage:
#   rofi-radio.sh
# -----------------------------------------------------------------------------
# Script:

# From: https://stackoverflow.com/questions/5014632/how-can-i-parse-a-yaml-file-from-a-linux-shell-script
function parse_yaml {
   local prefix=$2
   local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
   sed -ne "s|^\($s\):|\1|" \
        -e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \
        -e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p"  $1 |
   awk -F$fs '{
      indent = length($1)/2;
      vname[indent] = $2;
      for (i in vname) {if (i > indent) {delete vname[i]}}
      if (length($3) > 0) {
         vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
         printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
      }
   }'
}

# Stations directory
STATIONS_FILE=~/.config/stations.yml

# Save find result to F_ARRAY
readarray -t F_ARRAY <<< $(parse_yaml $STATIONS_FILE)

# Associative array for storing stations
# key => station name
# value => absolute path to the file
# STATIONS['filename']='path'
declare -A STATIONS

# Add elements to STATIONS array
get_stations() {

  # if [ ${#F_ARRAY[@]} != 0 ]; then
  if [[ ! -z ${F_ARRAY[@]} ]]; then
    for i in "${!F_ARRAY[@]}"
    do
      path=${F_ARRAY[$i]}
      file=$(basename "${F_ARRAY[$i]}")
      STATIONS+=(["$file"]="$path")
    done
  else
      echo "$STATIONS_DIR is empty!"
      echo "Please put some stations in it."
      echo "Only .pdf files are accepted."
      exit
  fi

  
}

# List for rofi
gen_list(){
  for i in "${!STATIONS[@]}"
  do
    echo "$i"
  done
}

main() {
  get_stations
  station=$( (gen_list) | rofi -dmenu -i -matching fuzzy -no-custom -location 0 -p "Book > " )

  if [ -n "$station" ]; then
    echo $station
    echo $STATIONS[$station]
  fi
}

main

exit 0
