#!/bin/bash

# This is a modified version of sway-interactive-screenshot made by moverest
# https://github.com/moverest/sway-interactive-screenshot/


# `list_geometry` returns the geometry of the focused of visible windows. You can also get they title
# by setting a second argument to `with_description`. The geometry and the title are seperated by `\t`.
#
# Arguments:
#   $1: `focused` or `visible`
#   $2: `with_description` or nothing
#
# Output examples:
#   - with the `with_description` option:
#      12,43 100x200\tTermite
#   - without the `with_description` option:
#      12,43 100x200

function list_geometry () {
	[ "$2" = with_description ] && local append="\t\(.name)" || local append=
	swaymsg -t get_tree | jq -r '.. | (.nodes? // empty)[] | select(.'$1' and .pid) | "\(.rect.x),\(.rect.y) \(.rect.width)x\(.rect.height)'$append'"'
}


# WINDOWS=`list_geometry visible with_description`
WINDOWS=`list_geometry visible with_description | screenshot-wofi-text-align`
FOCUSED=`list_geometry focused`

# CHOICE=`rofi -dmenu -i -p 'Screenshot' << EOF
CHOICE=`wofi -i -d -W 800 -p 'Screenshot' << EOF
Focused Window
Focused Screen
All Screens
Region
$WINDOWS
EOF`


SAVEDIR="$(xdg-user-dir PICTURES)/Screenshots"
mkdir -p "$SAVEDIR"
FILENAME="$SAVEDIR/$(date +'Screenshot %Y-%m-%d %H:%M:%S.png')"
EXPANDED_FILENAME="${FILENAME/#\~/$HOME}"

case $CHOICE in
    'All Screens')
        grim "$EXPANDED_FILENAME"
	;;
    'Focused Screen')
        grim -o "$(swaymsg -t get_outputs | jq -r '.[] | select(.focused) | .name')" "$EXPANDED_FILENAME"
        ;;
    Region)
        grim -g "$(slurp)" "$EXPANDED_FILENAME"
	;;
    'Focused Window')
        grim -g "$FOCUSED" "$EXPANDED_FILENAME"
	;;
    '')
        # notify-send "Screenshot" "Cancelled"
        exit 0
        ;;
    *)
    	GEOMETRY="`echo \"$CHOICE\" | cut -d$'\t' -f1`"
        grim -g "$GEOMETRY" "$EXPANDED_FILENAME"
esac

wl-copy < $(echo "$EXPANDED_FILENAME")
notify-send "Screenshot" "File saved as <i>'$FILENAME'</i> and copied to the clipboard." -i "$EXPANDED_FILENAME"