#!/bin/bash

ICON="/usr/share/icons/hicolor/48x48/apps/click-radio.png"
EICON="/usr/share/click-radio/icons/error.svg"
CONF="$HOME/.config/clickradio"

# Kill any previously running playlist process
pkill -f playlist
pkill -f searchweb
PID=`ps -eaf | grep yad | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
kill -9 $PID > /dev/null 2>&1
fi &
# Browser detection function
detect_browser() {
    local browsers=(brave chrome chromium edge firefox opera safari vivaldi whale)
    for b in "${browsers[@]}"; do
        if command -v "$b" &>/dev/null; then
            echo "$b"
            return 0
        fi
    done
    return 1
}

# YAD form dialog
while :; do
    ENTRY=$(yad --width=525 --window-icon="$ICON" \
        --on-top --center \
        --form --title="YouTube Downloader" \
        --field="Add Link:" "" \
        --field="Save in:DIR" "$HOME/Downloads" \
        --field="Rename (optional):" "" \
        --field="Audio Download:chk" FALSE \
        --button="Cancel"!/usr/share/click-radio/icons/cancel.svg:1 \
        --button="Ok"!/usr/share/click-radio/icons/ok.svg:0)
    if [ $? = 1 ]; then
    exit
    fi
    [[ $? -ne 0 ]] && exit

    IFS="|" read -r URL SAVEDIR RENAME AUDIOONLY <<< "$ENTRY"

    URL=$(echo "$URL" | sed 's/[&?].*//' | awk '{print $1}')

    if [[ -z "$URL" || -z "$SAVEDIR" ]]; then
        yad --error --width=400 --height=90 --fixed --on-top --center --title="Error" \
            --text="\nNo input for URL or information is missing!" --window-icon="$EICON" --image="$ICON" \
            --button="gtk-ok"
        continue
    fi

    break
done

cd "$SAVEDIR" || exit 1

BROWSER=$(detect_browser)
if [[ -z "$BROWSER" ]]; then
    yad --error --title="Browser Check" --window-icon=error \
    --height=100 --width=500 --fixed --on-top --center \
    --text="\n<b>No supported browser found on your system for downloading.\nSupported</b>: brave, chrome, chromium, edge, firefox, opera, safari, vivaldi and whale    \n" --button="gtk-ok"
    exit 1
fi
#--js-runtimes deno
# Set file type and output format
if [[ "$AUDIOONLY" == "TRUE" ]]; then
    FORMAT_ARGS=(-t mp3)
    FILETYPE="mp3"
    TITLE="YouTube Audio Downloader"
    MSG="Downloading mp3 audio file... Please wait!"
    EXT="mp3"
else
    FORMAT_ARGS=(-t mp4)
    FILETYPE="mp4"
    TITLE="YouTube Video Downloader"
    MSG="Downloading mp4 video file... Please wait!"
    EXT="mp4"
fi

# Construct output filename pattern
if [[ -n "$RENAME" ]]; then
    OUTPUT_FILE="${RENAME// /" "}.%(ext)s"
else
    OUTPUT_FILE="%(title).80s.%(ext)s"
fi

# Run download with percentage progress
PYTHONUNBUFFERED=1 yt-dlp "${FORMAT_ARGS[@]}" -o "$OUTPUT_FILE" "$URL" \
    --newline \
    --progress-template "download:%(progress._percent_str)s" 2>&1 |
while IFS= read -r line; do
    echo "$line" >&2  # Debugging
    if [[ "$line" =~ Destination:\ (.+)$ ]]; then
        fullfile=$(basename "${BASH_REMATCH[1]}")
        shortname=$(echo "$fullfile" | cut -c1-50)
       [[ "${#fullfile}" -gt 50 ]] && shortname="$shortname..."
    fi
for ((i=1; i<=100; i++)); do { echo "#" && sleep 0.1; } done|echo "#"
done | $(yad --progress --pulsate \
    --title="$TITLE" \
    --text="\n$MSG" \
    --auto-close --width=450 --center --fixed \
    --window-icon="$ICON" --image="$ICON" \
    --button="Cancel"!/usr/share/click-radio/icons/cancel.svg)

# If yt-dlp failed
if [[ $? -ne 0 ]]; then
    yad --error --width=450 --fixed --height=100 --center --title="Download Error" \
        --text="\nFailed to download from URL. Check the URL and try again." \
        --window-icon="$EICON" --image="$EICON" --button="gtk-ok"
    exit 1
fi

# Clean up filenames (remove brackets, parentheses, extra spaces)
rename -E 's/\s*\[[^]]*\]//g; s/\s*\([^)]*\)//g; s/\s+(\.mp[34])$/$1/' "$SAVEDIR"/*.{mp3,mp4} 2>/dev/null
rm -f "$SAVEDIR"/*.webm "$SAVEDIR"/*.part 2>/dev/null

# Find the latest downloaded file
downloaded_file=$(ls -t "$SAVEDIR"/*."$EXT" 2>/dev/null | head -n 1)

if [[ -z "$downloaded_file" || ! -f "$downloaded_file" ]]; then
    yad --error --width=450 --fixed --height=100 --center --title="Download Failed" \
        --text="\nThe $FILETYPE file was not found. Please try again." \
        --window-icon="$EICON" --image="$EICON" --button="gtk-ok"
    exit 1
else
NAME=$(ls -t $SAVEDIR/*."$EXT"| sed 's/.*\///' 2>/dev/null | head -n 1)
    yad --width=450 --fixed --height=100 --center --title="Download Complete" \
        --text="\nSaved in $SAVEDIR\n<span color=\"#BE7F00\"><b>$NAME</b></span>" \
        --window-icon="$ICON" --image=$ICON --button="gtk-ok"
    exit 0
fi

