#!/bin/bash

SOCKET="/tmp/mpvsocket"

# Check if the mpv socket exists
if [[ ! -S "$SOCKET" ]]; then
  echo " mpv socket not found at $SOCKET"
  exit 1
fi

send_cmd() {
  echo "$1" | socat - "$SOCKET"
}

get_prop() {
  send_cmd "{ \"command\": [\"get_property\", \"$1\"] }" | jq -r '.data'
}

format_time() {
  local time=$1
  if [[ $time == null || -z $time ]]; then
    echo "--:--"
  else
    printf '%02d:%02d' $((time / 60)) $((time % 60))
  fi
}

while true; do
  clear

  # Get dynamic info
  title=$(get_prop "media-title")
  position=$(get_prop "playback-time")
  duration=$(get_prop "duration")

  pos_fmt=$(format_time "$position")
  dur_fmt=$(format_time "$duration")

  echo " MPV Controller"
  echo "=========================="
  echo " Title    : ${title:-Unknown}"
  echo "Position : ${pos_fmt} / ${dur_fmt}"
  echo "=========================="
  echo "1) Pause / Resume"
  echo "2) Next file"
  echo "3) Previous file"
  echo "4) Increase volume"
  echo "5) Decrease volume"
  echo "6) Mute / Unmute"
  echo "7) Seek forward 10s"
  echo "8) Seek backward 10s"
  echo "0) Exit"
  echo "=========================="
  read -rp "Choose an option: " opt

  case "$opt" in
    1) send_cmd '{ "command": ["cycle", "pause"] }' ;;
    2) send_cmd '{ "command": ["playlist-next"] }' ;;
    3) send_cmd '{ "command": ["playlist-prev"] }' ;;
    4) send_cmd '{ "command": ["add", "volume", 5] }' ;;
    5) send_cmd '{ "command": ["add", "volume", -5] }' ;;
    6) send_cmd '{ "command": ["cycle", "mute"] }' ;;
    7) send_cmd '{ "command": ["seek", 10, "relative"] }' ;;
    8) send_cmd '{ "command": ["seek", -10, "relative"] }' ;;
    0) echo " Exiting..."; break ;;
    *) echo " Invalid option"; sleep 1 ;;
  esac

  read -rp "Press Enter to continue..."
done

