#!/usr/bin/env bash

set -e
set -o nounset
set -o pipefail

SCRIPTS=${SCRIPTS:-$HOME/.local/scripts}
THIS_FILE=${BASH_SOURCE[0]}
LOG_LABEL=$(basename "$THIS_FILE")
THIS=${THIS:-$LOG_LABEL}
LOG_FILE=${LOG_FILE:-"$LOG_LABEL.log"}

address=""
width=""
height=""

usage() {
  cat <<EOF

Utility for toggling a windows floating property.

If no address is supplied and '--active' flag is not set, then we will read address from stdin.

USAGE:

  $ $THIS <flags> <address>

FLAGS:
  -a | --active:        Toggles floating of the active window.
  -w | --width <n>:     Set a width of the floating window, can be pixels or percent (ex. 80%).
  -h | --height <n>:    Set a height of the floating window, can be pixels or percent (ex. 80%).
  --help:               Show this help page.

EOF

}

log() {
  logging log --source "$THIS_FILE" "$@"
}

# Suppress output of hyprctl
hypr_dispatch() {
  hyprctl dispatch "$@" >/dev/null 2>&1 && return $?
}

toggle_floating() {
  hypr_dispatch togglefloating "address:$address"
}

resize_window() {
  if [[ -n $width ]] && [[ -n $height ]]; then
    log "Resizing window: width: $width, height: $height"
    hypr_dispatch resizewindowpixel exact "$width $height,address:$address"
  fi

  echo "$address"

}

center_window() {
  local address=""
  read -r address
  local activeaddress=$(hyprctl activewindow -j | jq -r '.address')
  if [[ $address == $activeaddress ]]; then
    log "Centering window..."
    hypr_dispatch centerwindow
  fi
}

################################################################################
# MAIN
################################################################################

# Setup logging
source "$SCRIPTS/hypr/logging"
setup-logging "$LOG_FILE" "$LOG_LABEL"

while [[ $# -gt 0 ]]; do
  if [[ $1 == "--help" ]]; then
    usage && exit 0
  elif [[ $1 == "-w" ]] || [[ $1 == "--width" ]]; then
    shift
    width=$1
  elif [[ $1 == "-h" ]] || [[ $1 == "--height" ]]; then
    shift
    height=$1
  elif [[ $1 == "-a" ]] || [[ $1 == "--active" ]]; then
    address=$(hyprctl activewindow -j | jq -r '.address')
  else
    address=$1
  fi
  shift
done

if [[ -z $address ]]; then
  read -p "Window address: " address
fi

if [[ -z $address ]]; then
  log --error "No address was supplied" && exit 1
fi

log "Begin toggling floating for: '$address'"

floating=$(hyprctl clients -j | jq ".[] | select(.address == \"$address\") | .floating")
log "Is currently floating: $floating"

toggle_floating

if [ ! "$floating" == "true" ]; then
  resize_window | center_window
fi
