#!/bin/sh

menu() {
	bemenu --fn 'IBM Plex Sans 15' -i -c -W "0.${2:-2}" -B 3 -l 10 -p "$1" --bdr="#$GLOBAL_ACCENT" --tf="#$GLOBAL_ACCENT" --hf="#$GLOBAL_ACCENT" -R 20
}

setup_dual_monitor() {
	monitor="$1"
	[ -z "$monitor" ] && monitor=$(hyprctl monitors | sed -nE 's|.*(HDMI-A-[0-9]).*|\1|p')
	[ -z "$monitor" ] && monitor=$(hyprctl monitors | sed -nE 's|.* (DP-[0-9]).*|\1|p')
	position=$(printf "auto\nauto-left" | menu "[$monitor] position:")
	if [ -n "$monitor" ]; then
		notify-send -e "Setting up dual monitor workflow"
		hyprctl keyword monitor "$monitor",highres,"$position",1
		hyprctl dispatch moveworkspacetomonitor "1 0"
		hyprctl dispatch moveworkspacetomonitor "2 0"
		hyprctl dispatch moveworkspacetomonitor "3 1"
		hyprctl dispatch moveworkspacetomonitor "4 1"
		eww kill
		eww open-many time_1 music_1
	fi
}

handle_it() {
	[ -z "$1" ] || notify-send -e "$1"
	monitor=$(printf '%s' "$1" | sed -nE 's|monitoraddedv2>>[0-9]*,([^,]*),.*|\1|p')
	choice=$(printf "Extend\nMirror" | menu "[$monitor] mode:")
	[ -z "$choice" ] && return 0
	notify-send -e "${choice}ing screen"
	if [ "$choice" = "Extend" ]; then
		setup_dual_monitor "$monitor"
	else
		hyprctl keyword monitor "$monitor",preferred,auto,1,mirror,eDP-1
	fi
}

case $1 in
	list)
		#only lists the open applications with their workspace number so u can safely close them
		i=4
		while [ $i -gt 0 ]; do
			notify-send -e -i "lol" "Running Apps" "$(hyprctl clients | tr '\n' ',' | sed 's|,,|\n|g' | sed -nE 's|.*workspace: ([0-9]).*class: ([^,]*).*xwayland: ([^,]).*|workspace \1: \2 (xway: \3)|p')" -h "string:x-canonical-private-synchronous:${0##*/}" -t 1500
			: $((i -= 1))
			sleep 1
		done
		;;
	focus)
		#shows the workspace number as notification whenever u switch workspaces and also handles the dual monitor setup on the fly(perfect for laptop users)
		socat -u "UNIX-CONNECT:$XDG_RUNTIME_DIR/hypr/$HYPRLAND_INSTANCE_SIGNATURE/.socket2.sock" - | while read -r line; do
			printf "%s" "$line" | grep -qE "monitoraddedv2.*HEADLESS" && continue
			printf "%s" "$line" | grep -q "monitoraddedv2" && handle_it "$line"
			#recent workspace switcher
			current=$(printf "%s" "$line" | sed -nE 's_^(workspace)v2>>([^,]*),.*_\1 \2_p')
			[ -n "$current" ] && notify-send -e -i "lol" "$current" -h "string:x-canonical-private-synchronous:monitor" -t 700 2>/dev/null
		done
		;;
	toggle)
		#toggle between mirror and extend setup. this function should be keybinded
		handle_it
		;;
	*)
		#to be executed once after booting to setup dual montiors by default if the monitor is connected
		setup_dual_monitor
		;;
esac
