#!/usr/bin/env bash

XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
XDG_STATE_HOME="${XDG_STATE_HOME:-$HOME/.local/state}"
CONFIG_DIR="$XDG_CONFIG_HOME/ags"
HYPRLOCK_CONF_TEMPLATE="$CONFIG_DIR/scripts/templates/hypr/hyprlock.conf"
HYPRLOCK_CONF="$XDG_CONFIG_HOME/hypr/hyprlock.conf"

THUMBNAIL_DIR="/tmp/mpvpaper_thumbnails"
CUSTOM_DIR="$XDG_CONFIG_HOME/hypr/custom"
RESTORE_SCRIPT_DIR="$CUSTOM_DIR/scripts"
RESTORE_SCRIPT="$RESTORE_SCRIPT_DIR/__restore_video_wallpaper.sh"

VIDEO_OPTS="no-audio loop hwdec=auto scale=bilinear interpolation=no video-sync=display-resample panscan=1.0 video-scale-x=1.0 video-scale-y=1.0 video-align-x=0.5 video-align-y=0.5"

mkdir -p "$THUMBNAIL_DIR"
mkdir -p "$RESTORE_SCRIPT_DIR"

is_video() {
	local extension="${1##*.}"
	[[ "$extension" == "mp4" || "$extension" == "mkv" || "$extension" == "webm" ]] && return 0 || return 1
}

kill_existing_mpvpaper() {
    # Abort all mpvpapers' instance
    pkill -f -9 mpvpaper || true
}

create_restore_script() {
	local video_path=$1

	cat > "$RESTORE_SCRIPT.tmp" << EOF
#!/bin/bash
# Generated by switchwall.sh - Don't modify it by yourself.
# Time: $(date)

pkill -f -9 mpvpaper

for monitor in \$(hyprctl monitors -j | jq -r '.[] | .name'); do
    mpvpaper -o "$VIDEO_OPTS" "\$monitor" "$video_path" &
    sleep 0.1
done
EOF

	mv "$RESTORE_SCRIPT.tmp" "$RESTORE_SCRIPT"
	chmod +x "$RESTORE_SCRIPT"
}

remove_restore() {
	cat > "$RESTORE_SCRIPT.tmp" << EOF
#!/bin/bash
# The content of this script will be generated by switchwall.sh - Don't modify it by yourself.
EOF

	mv "$RESTORE_SCRIPT.tmp" "$RESTORE_SCRIPT"
}

update_hyprlock_wallpaper() {
	local imgpath=$1
	local thumbnail=$2

	# If thumbnail is provided (for videos), use it. Otherwise use the original image
	local wallpath=${thumbnail:-$imgpath}

	# Store a copy of the current wallpaper path for other processes
	mkdir -p "$(dirname "$XDG_CONFIG_HOME/hypr/current_wallpaper.txt")"
	echo "$wallpath" > "$XDG_CONFIG_HOME/hypr/current_wallpaper.txt"

	# Update the path directly in hyprlock.conf
	sed -i "s|path = .*$|path = $wallpath|" "$HYPRLOCK_CONF"

	# Debug: output the new wallpaper path
	echo "Updated hyprlock wallpaper path to: $wallpath"
}

switch() {
	imgpath=$1
	read scale screenx screeny screensizey < <(hyprctl monitors -j | jq '.[] | select(.focused) | .scale, .x, .y, .height' | xargs)
	cursorposx=$(hyprctl cursorpos -j | jq '.x' 2>/dev/null) || cursorposx=960
	cursorposx=$(bc <<< "scale=0; ($cursorposx - $screenx) * $scale / 1")
	cursorposy=$(hyprctl cursorpos -j | jq '.y' 2>/dev/null) || cursorposy=540
	cursorposy=$(bc <<< "scale=0; ($cursorposy - $screeny) * $scale / 1")
	cursorposy_inverted=$((screensizey - cursorposy))

	if [ "$imgpath" == '' ]; then
		echo 'Aborted'
		exit 0
	fi

	kill_existing_mpvpaper

	if is_video "$imgpath"; then
		missing_deps=()
		if ! command -v mpvpaper &> /dev/null; then
			missing_deps+=("mpvpaper")
		fi

		if ! command -v ffmpeg &> /dev/null; then
			missing_deps+=("ffmpeg")
		fi

		if [ ${#missing_deps[@]} -gt 0 ]; then
			echo "Missing deps: ${missing_deps[*]}"
			echo "Arch: "
			echo "	yay -S ${missing_deps[*]}"
			exit 0
		fi

		local video_path=$1

		monitors=$(hyprctl monitors -j | jq -r '.[] | .name')

		for monitor in $monitors; do
			mpvpaper -o "$VIDEO_OPTS" "$monitor" "$video_path" &
			sleep 0.1
		done

		# We take the first frame of video to colorgen
		thumbnail="$THUMBNAIL_DIR/$(basename "$imgpath").jpg"
		ffmpeg -y -i "$imgpath" -vframes 1 "$thumbnail" 2>/dev/null

		if [ -f "$thumbnail" ]; then
			"$CONFIG_DIR"/scripts/color_generation/colorgen.sh "$thumbnail" --apply --smart
			create_restore_script "$video_path"
			update_hyprlock_wallpaper "$imgpath" "$thumbnail"
		else
			echo "Cannot create image to colorgen"
		fi
	else
		# agsv1 run-js "wallpaper.set('')"
		# sleep 0.1 && agsv1 run-js "wallpaper.set('${imgpath}')" &
		swww img "$imgpath" --transition-step 100 --transition-fps 120 \
			--transition-type grow --transition-angle 30 --transition-duration 1 \
			--transition-pos "$cursorposx, $cursorposy_inverted"

		"$CONFIG_DIR"/scripts/color_generation/colorgen.sh "$imgpath" --apply --smart
		remove_restore
		update_hyprlock_wallpaper "$imgpath"
	fi
}

if [ "$1" == "--noswitch" ]; then
	if pgrep -f mpvpaper > /dev/null; then
		imgpath=$(ps -eo cmd | grep mpvpaper | grep -v grep | awk '{for(i=NF;i>0;i--) if($i!~/^-/) {print $i; break}}')
	else
		imgpath=$(swww query | awk -F 'image: ' '{print $2}')
		# imgpath=$(agsv1 run-js 'wallpaper.get(0)')
	fi
elif [[ "$1" ]]; then
	switch "$1"
else
	# Select and set image (hyprland)

    cd "$(xdg-user-dir PICTURES)/Wallpapers" || cd "$(xdg-user-dir PICTURES)" || return 1
	switch "$(yad --width 1200 --height 800 --file --add-preview --large-preview --title='Choose wallpaper')"
fi
