#!/usr/bin/env bash
set -u

DOWNLOAD_DIR="$HOME/Downloads/Video Downloader/Selected Downloads"
USER_DATA="$HOME/.local/share/video-downloader"
PACKAGE_NAME="video-downloader"

show_error() {
    zenity --error --title="Video Downloader" --width=500 --text="$1" 2>/dev/null || true
}

show_info() {
    zenity --info --title="Video Downloader" --width=500 --text="$1" 2>/dev/null || true
}

installed_version() {
    dpkg-query -W -f='${Version}' "$PACKAGE_NAME" 2>/dev/null || true
}

candidate_version() {
    apt-cache policy "$PACKAGE_NAME" 2>/dev/null \
        | awk '/Candidate:/ {print $2; exit}'
}

update_available() {
    local installed candidate
    installed="$(installed_version)"
    candidate="$(candidate_version)"
    [ -n "$installed" ] || return 1
    [ -n "$candidate" ] || return 1
    [ "$candidate" != "(none)" ] || return 1
    dpkg --compare-versions "$candidate" gt "$installed"
}

friendly_version() {
    local version="$1"
    version="${version#*:}"
    version="${version#1.3.0~}"
    printf '%s' "$version"
}

perform_update() {
    local installed candidate
    installed="$(installed_version)"
    candidate="$(candidate_version)"

    if ! update_available; then
        show_info "<b>Video Downloader is up to date.</b>\n\nYou're already using the latest available version."
        return
    fi

    if ! zenity --question \
        --title="Video Downloader Update" --width=510 \
        --ok-label="Update Now" --cancel-label="Later" \
        --text="<b>A Video Downloader update is available.</b>\n\nInstalled: $(friendly_version "$installed")\nAvailable: $(friendly_version "$candidate")\n\nWould you like to install it now?" \
        2>/dev/null; then
        return
    fi

    if ! command -v pkexec >/dev/null 2>&1; then
        show_error "The system's graphical administrator prompt is not available.\n\nYou can install updates later through your system's Software Updater."
        return
    fi

    if pkexec /usr/bin/apt-get install --only-upgrade -y "$PACKAGE_NAME"; then
        show_info "<b>Video Downloader has been updated.</b>\n\nThe latest version is now installed."
        # Reload the newly installed manager in case this update replaced it.
        exec /usr/bin/video-downloader-manager
    else
        show_error "The update could not be installed.\n\nNothing has been removed. You can try again later."
    fi
}

check_for_updates() {
    if ! command -v pkexec >/dev/null 2>&1; then
        show_error "The system's graphical administrator prompt is not available.\n\nAutomatic system updates can still discover Video Downloader updates."
        return
    fi

    if ! pkexec /usr/bin/apt-get update; then
        show_error "Video Downloader couldn't check for updates right now.\n\nPlease check your internet connection and try again later."
        return
    fi

    if update_available; then
        perform_update
    else
        show_info "<b>Video Downloader is up to date.</b>\n\nYou're already using the latest available version."
    fi
}

auto_offer_update() {
    # Do not force a password prompt at startup. Ubuntu refreshes APT metadata
    # periodically; if that cache already knows about a newer SCARTLEAD build,
    # offer it immediately. Manual Check for Updates performs a fresh refresh.
    if update_available; then
        perform_update
    fi
}

open_downloader() {
    /usr/bin/video-downloader >/dev/null 2>&1 &
}

open_folder() {
    mkdir -p "$DOWNLOAD_DIR"
    if command -v xdg-open >/dev/null 2>&1; then
        xdg-open "$DOWNLOAD_DIR" >/dev/null 2>&1 &
    elif command -v gio >/dev/null 2>&1; then
        gio open "$DOWNLOAD_DIR" >/dev/null 2>&1 &
    else
        show_error "Your downloads are saved in:\n\n$DOWNLOAD_DIR"
    fi
}

uninstall_app() {
    if ! zenity --question \
        --title="Uninstall Video Downloader" --width=500 \
        --ok-label="Uninstall" --cancel-label="Cancel" \
        --text="<b>Remove Video Downloader from this computer?</b>\n\nYour downloaded videos and MP3 files will <b>not</b> be deleted." 2>/dev/null; then
        return
    fi

    if ! command -v pkexec >/dev/null 2>&1; then
        show_error "The system's graphical administrator prompt is not available.\n\nYou can still remove Video Downloader from your system's Software application."
        return
    fi

    if pkexec /usr/bin/apt-get remove -y "$PACKAGE_NAME"; then
        rm -rf "$USER_DATA/venv" "$USER_DATA/runtime" \
               "$USER_DATA/bgutil-ytdlp-pot-provider" "$USER_DATA/.bgutil-extract" \
               "$USER_DATA/logs" "$USER_DATA"/.setup-complete-* \
               "$USER_DATA"/bgutil-ytdlp-pot-provider-*.tar.gz "$USER_DATA/deno.zip" \
               2>/dev/null || true
        rmdir "$USER_DATA" 2>/dev/null || true

        zenity --info --title="Video Downloader" --width=470 \
            --text="<b>Video Downloader has been removed.</b>\n\nYour downloaded videos and MP3 files are still in your Downloads folder." \
            2>/dev/null || true
        exit 0
    else
        show_error "Video Downloader was not removed.\n\nNo downloaded videos or MP3 files were deleted."
    fi
}

auto_offer_update

while true; do
    choice="$(zenity --list \
        --title="Video Downloader" --width=540 --height=420 --hide-header \
        --column="Action" \
        --text="<b>Video Downloader</b>\nvideo downloader by scartlead.tv\n\nWhat would you like to do?" \
        "Open Video Downloader" "Open Downloads Folder" "Check for Updates" "Uninstall Video Downloader" \
        2>/dev/null)" || exit 0
    case "$choice" in
        "Open Video Downloader") open_downloader; exit 0 ;;
        "Open Downloads Folder") open_folder ;;
        "Check for Updates") check_for_updates ;;
        "Uninstall Video Downloader") uninstall_app ;;
    esac
done
