#!/usr/bin/env bash

FILES=$(echo -e "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS")

if [ -z "$FILES" ]; then
    zenity --error --text="No files selected."
    exit 1
fi

first_file=$(echo "$FILES" | head -n1)
EXT="${first_file##*.}"
EXT_LOWER=$(echo "$EXT" | tr '[:upper:]' '[:lower:]')

case "$EXT_LOWER" in
    jpg|jpeg|png|webp)
        MIME_CATEGORY="image"
        ;;
    pdf)
        MIME_CATEGORY="pdf"
        ;;
    mp3|ogg|wav|flac)
        MIME_CATEGORY="audio"
        ;;
    mp4|webm|avi|mkv)
        MIME_CATEGORY="video"
        ;;
    *)
        zenity --error --text="Unsupported file extension :("
        exit 1
        ;;
esac

case "$MIME_CATEGORY" in
    image)
        OPTIONS="JPEG\tjpg\nPNG\tpng\nWEBP\twebp\nPDF\tpdf"
        ;;
    pdf)
        OPTIONS="PDF\tpdf"
        ;;
    audio)
        OPTIONS="MP3\tmp3\nOGG\togg\nWAV\twav\nFLAC\tflac"
        ;;
    video)
        OPTIONS="MP4\tmp4\nWEBM\twebm\nAVI\tavi\nMKV\tmkv\nMP3\tmp3\nOGG\togg\nWAV\twav\nFLAC\tflac"
        ;;
esac

OUTPUT_EXT=$(zenity --list \
    --title="Convert $MIME_CATEGORY files" \
    --print-column=2 \
    --column="Format" --column="Extension" \
    $(echo -e "$OPTIONS"))

if [ -z "$OUTPUT_EXT" ]; then exit 0; fi

QUALITY=""
case "$OUTPUT_EXT" in
    jpg|jpeg)
        QUALITY=$(zenity --scale --title="Select JPEG quality (1-100)" --min-value=1 --max-value=100 --value=85)
        ;;
    mp3|ogg|wav)
        QUALITY=$(zenity --scale --title="Select audio bitrate (kbps)" --min-value=64 --max-value=320 --value=192 --step=16)
        ;;
    mp4|webm|avi|mkv)
        QUALITY=$(zenity --scale --title="Select video bitrate (kbps)" --min-value=500 --max-value=5000 --value=2000 --step=100)
        ;;
esac

total=$(echo "$FILES" | wc -l)
count=0

(
IFS=$'\n'
for FILE in $FILES; do
    count=$((count + 1))
    echo $(( count * 100 / total ))  # update progress bar
    echo "Converting: $(basename "$FILE")"

    DIR=$(dirname "$FILE")
    BASENAME=$(basename "$FILE")
    NAME="${BASENAME%.*}"
    OUTPUT_PATH="$DIR/$NAME.$OUTPUT_EXT"

    EXT="${FILE##*.}"
    EXT_LOWER=$(echo "$EXT" | tr '[:upper:]' '[:lower:]')
    case "$EXT_LOWER" in
        jpg|jpeg|png|webp)
            FILE_CATEGORY="image"
            ;;
        pdf)
            FILE_CATEGORY="pdf"
            ;;
        mp3|ogg|wav)
            FILE_CATEGORY="audio"
            ;;
        mp4|webm|avi|mkv)
            FILE_CATEGORY="video"
            ;;
        *)
            FILE_CATEGORY="unknown"
            ;;
    esac

    if [ "$FILE_CATEGORY" = "unknown" ]; then
        echo "Skipping unsupported file: $FILE" >&2
        continue
    fi

    # Run commands with error output visible (not silent)
    case "$FILE_CATEGORY" in
        image|pdf)
            if [ -n "$QUALITY" ] && [[ "$OUTPUT_EXT" == jpg || "$OUTPUT_EXT" == jpeg ]]; then
                convert "$FILE" -quality "$QUALITY" "$OUTPUT_PATH" || echo "Failed to convert $FILE" >&2
            else
                convert "$FILE" "$OUTPUT_PATH" || echo "Failed to convert $FILE" >&2
            fi
            ;;
        audio)
            if [ -n "$QUALITY" ]; then
                ffmpeg -loglevel error -y -i "$FILE" -b:a "${QUALITY}k" "$OUTPUT_PATH" || echo "Failed to convert $FILE" >&2
            else
                ffmpeg -loglevel error -y -i "$FILE" "$OUTPUT_PATH" || echo "Failed to convert $FILE" >&2
            fi
            ;;
        video)
            case "$OUTPUT_EXT" in
                mp3|ogg|wav)
                    if [ -n "$QUALITY" ]; then
                        ffmpeg -loglevel error -y -i "$FILE" -vn -b:a "${QUALITY}k" "$OUTPUT_PATH" || echo "Failed to convert $FILE" >&2
                    else
                        ffmpeg -loglevel error -y -i "$FILE" -vn "$OUTPUT_PATH" || echo "Failed to convert $FILE" >&2
                    fi
                    ;;
                *)
                    if [ -n "$QUALITY" ]; then
                        ffmpeg -loglevel error -y -i "$FILE" -b:v "${QUALITY}k" "$OUTPUT_PATH" || echo "Failed to convert $FILE" >&2
                    else
                        ffmpeg -loglevel error -y -i "$FILE" "$OUTPUT_PATH" || echo "Failed to convert $FILE" >&2
                    fi
                    ;;
            esac
            ;;
    esac

done
) | zenity --progress --title="Batch converting files..." --percentage=0 --auto-close --width=400
