#!/bin/bash

NOTIFY_CMD="notify-send -i "shoot" -t 10000 -A open=Open -A delete=Delete -A edit=Edit *click*"

TARGET_DIRECTORY="$(xdg-user-dir)/Pictures/Screenshots"

SOURCE="${1:-area}"
TEMP_FILE="/tmp/screenshot.png"

getGrimArea() {
  case $SOURCE in
  area)
    workspaces=$(hyprctl -j monitors | jq -r 'map(".workspace.id == \(.activeWorkspace.id)") | join(" or ")')
    hyprctl -j clients |
      jq -r ".[] | select($workspaces) | \"\(.at[0]),\(.at[1]) \(.size[0])x\(.size[1]) \(.class)\"" |
      slurp -b "#11111177" -c "#1090ffff" -d -F mono
    ;;
  active)
    hyprctl -j activewindow | jq -r '"\(.at[0]),\(.at[1]) \(.size[0])x\(.size[1])"'
    ;;
  esac
  return $?
}

targetFolder=""
if [[ $SOURCE == "active" ]]; then
  targetFolder="/$(hyprctl -j activewindow | jq -r '(.class)')"
fi

targetPath="$TARGET_DIRECTORY$targetFolder"
mkdir -m 0744 -p "$targetPath"

targetPath="$targetPath/$(date "+%d-%b_%H-%M-%S").png"

area="$(getGrimArea)"
if [[ $? != 0 ]]; then
  exit
fi
if [[ "$area" == 'invalid geometry' ]]; then
  exit
fi
echo "$area"

sleep 0.1
grim -g "$area" "$targetPath"

wl-copy <"$targetPath"

response=$(
  ${NOTIFY_CMD} "Took screenshot"
)
echo "Responded with '$response'"

case "$response" in
delete)
  rm "$targetPath"
  ;;
edit)
  hyprctl dispatch exec pinta "$targetPath" &
  ;;
open)
  hyprctl dispatch exec xdg-open "$targetPath" &
  ;;
esac
