#!/usr/bin/env bash

NOTI_ST=string:np:error
NOTI_TIME=5000

for i in "playerctl" "wl-copy" "hyprctl" "notify-send"; do
  if builtin type -P "$i" &> /dev/null; then continue; fi

  notify-send -h $NOTI_ST -t $NOTI_TIME "Missing dependencies, can't record.";
  echo "Missing dependencies."
  exit 1
done

players="$(playerctl -l 2>&1)"
if echo "$players" | grep 'No players found'; then
  notify-send -h $NOTI_ST -t $NOTI_TIME "No active player"
  exit 1
fi

player="$(echo "$players" | grep spot | head -n 1)"
if [ -z "$player" ]; then
  player="$(echo "$players" | head -n 1)"
fi


data=$(playerctl metadata -p "$player" --format $'{{title}}\x1F{{xesam:url}}\x1F{{artist}}\x1F{{album}}')
IFS=$'\x1F' read -r title url artist album <<< "$data"
output=$'## Now Playing\n>'

if [ -z "$title" ]; then
  notify-send -h $NOTI_ST -t $NOTI_TIME "This song doesn't have a title. Not much to do here.";
  exit 1;
fi
if [ -z "$url" ]; then
  output="$output $title"
else
  output="$output [$title](<$url>)"$'\n'
fi
if [ -n "$artist" ]; then
  output="$output\- **$artist**"
fi
if [ -n "$artist" ] && [ -n "$album" ]; then
  output="$output on *$album*" 
fi

echo "$output" | wl-copy
  
hyprctl dispatch sendshortcut "CTRL,V,"
if [[ "$@" == "1" ]]; then
  hyprctl dispatch sendshortcut ",Return,"
fi
