#!/bin/bash

# omarchy:summary=Configure the app dock
# omarchy:group=dock
# omarchy:subcommand=position [top|bottom|left|right] — Set the dock position, or print it when given none
# omarchy:subcommand=visibility [always|first-app|hidden|off] — Keep the dock out always, until the workspace has a window, or only while the pointer is at its edge, or turn it off; prints the setting when given none
# omarchy:subcommand=background [auto|glassy|none] — Stand the dock's icons on a glassy shelf that blurs what is behind it: once the workspace has a window, always, or never; prints the setting when given none
# omarchy:subcommand=pinned [<desktop-id>...] — Set the pinned apps in dock order, or print them
# omarchy:subcommand=pin <desktop-id> — Keep an app in the dock
# omarchy:subcommand=unpin <desktop-id> — Remove an app from the dock
# omarchy:subcommand=defaults — Restore the default dock settings and pinned apps
# omarchy:examples=omarchy dock position left | omarchy dock visibility always | omarchy dock pin folio

set -euo pipefail

source omarchy-shell-config

usage() {
  cat <<USAGE
Usage: omarchy dock <command> [args...]

  position [top|bottom|left|right]     Dock position; prints the current one
                                       when given none
  visibility [always|first-app|hidden|off]
                                       When the dock is out: always, until the
                                       workspace has a window, only while the
                                       pointer is at its edge, or never; prints
                                       the setting when given none
  background [auto|glassy|none]        Dock background: glassy stands the
                                       icons on a shelf that blurs what is
                                       behind the dock, none leaves them
                                       clear, and auto is clear until the
                                       workspace has a window; prints the
                                       setting when given none
  pinned [<desktop-id>...]             Pinned desktop ids in dock order; prints
                                       them one per line when given none
  pin <desktop-id>                     Keep an app in the dock
  unpin <desktop-id>                   Remove an app from the dock
  defaults                             Restore the default dock settings and
                                       pinned apps
USAGE
}

# A shell.json without pins of its own uses the default pins, so pinning or
# unpinning starts from those rather than from an empty dock.
PINNED='(.dock.pinned // $defaults[0].dock.pinned // [])'

cmd_position() {
  if (( $# == 0 )); then
    jq -r '.dock.position // "bottom"' "$(source_file)"
    return
  fi

  local position="$1"
  (( $# == 1 )) || fail "position takes a single value"
  [[ $position =~ ^(top|bottom|left|right)$ ]] || fail "position must be top, bottom, left, or right"
  commit "$NORMALIZE | .dock.position = \$position" --arg position "$position"
  echo "Dock position set to $position"
}

# Minimized windows wait for the dock to bring them back, so with it turned off
# they return to the workspaces they left.
restore_minimized() {
  local address workspace
  while read -r address workspace; do
    hyprctl dispatch "hl.dsp.window.move({ workspace = \"$workspace\", follow = false, window = \"address:$address\" })" >/dev/null
  done < <(hyprctl clients -j 2>/dev/null | jq -r '.[]
    | select(.workspace.name == "special:minimized")
    | "\(.address) \(first((.tags // [])[] | select(test("^omarchy-minimized-from-[0-9]+$")) | sub("^omarchy-minimized-from-"; "")))"')
}

# A shell.json from before this setting said autohide, which hid the dock
# always; without either, the dock hides once its workspace has a window.
cmd_visibility() {
  if (( $# == 0 )); then
    jq -r '.dock.visibility // (if .dock.autohide == true then "hidden" else "first-app" end)' "$(source_file)"
    return
  fi

  local visibility="$1"
  (( $# == 1 )) || fail "visibility takes a single value"
  [[ $visibility =~ ^(always|first-app|hidden|off)$ ]] || fail "visibility must be always, first-app, hidden, or off"
  commit "$NORMALIZE | .dock.visibility = \$visibility | del(.dock.autohide)" --arg visibility "$visibility"
  [[ $visibility != "off" ]] || restore_minimized
  sync_glass
  echo "Dock visibility set to $visibility"
}

cmd_pinned() {
  if (( $# == 0 )); then
    jq -r --slurpfile defaults "$DEFAULTS_FILE" "$PINNED | .[]" "$(source_file)"
    return
  fi

  local ids=() id
  for id in "$@"; do
    ids+=("$(desktop_id "$id")")
  done
  commit "$NORMALIZE | .dock.pinned = (\$ids | reduce .[] as \$id ([]; if index([\$id]) then . else . + [\$id] end))" \
    --argjson ids "$(printf '%s\n' "${ids[@]}" | jq -R . | jq -s .)"
  echo "Set the apps pinned to the dock"
}

desktop_id() {
  (( $# == 1 )) || fail "takes a single desktop id"
  local id="${1%.desktop}"
  [[ -n $id ]] || fail "desktop id must not be empty"
  printf '%s\n' "$id"
}

cmd_pin() {
  local id
  id=$(desktop_id "$@")
  commit "$NORMALIZE | .dock.pinned = ($PINNED | if index([\$id]) then . else . + [\$id] end)" \
    --arg id "$id" --slurpfile defaults "$DEFAULTS_FILE"
  echo "Pinned $id to the dock"
}

cmd_unpin() {
  local id
  id=$(desktop_id "$@")
  commit "$NORMALIZE | .dock.pinned = ($PINNED | map(select(. != \$id)))" \
    --arg id "$id" --slurpfile defaults "$DEFAULTS_FILE"
  echo "Unpinned $id from the dock"
}

# Hyprland blurs behind the dock only while the dock-glassy toggle is on, so it
# follows a dock that is turned on and may show its shelf, reloading Hyprland
# only when it changes. The toggle sits where Hyprland reads it, under XDG_STATE_HOME, as the
# bar's does. A shell.json that can't be read changes nothing.
sync_glass() {
  local dir="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/toggles/hypr"
  local flag="$dir/dock-glassy.lua"
  local background visibility

  background=$(cmd_background) && visibility=$(cmd_visibility) || return 1
  [[ -n $background && -n $visibility ]] || return 1
  if [[ $background != "none" && $visibility != "off" ]]; then
    [[ ! -f $flag ]] || return 0
    mkdir -p "$dir" && cp "$OMARCHY_PATH/default/hypr/toggles/dock-glassy.lua" "$flag" || return 1
  else
    [[ -f $flag ]] || return 0
    rm -f "$flag" || return 1
  fi

  # The shell syncs as it starts, which an update does right after replacing
  # Hyprland's binary; that session picks the toggle up when it next reloads.
  OMARCHY_RELOAD_SKIP_REPLACED=1 omarchy-restart-hyprctl
}

# The dock background is auto, glassy or none, and auto when never
# chosen. A shell.json from before it had one may say backdrop true or false
# instead, which is glassy or none, and setting a background drops it.
cmd_background() {
  if (( $# == 0 )); then
    jq -r '.dock.background // (if .dock.backdrop == false then "none" elif .dock.backdrop == true then "glassy" else "auto" end)' "$(source_file)"
    return
  fi

  local background="$1"
  (( $# == 1 )) || fail "background takes a single value"
  [[ $background =~ ^(auto|glassy|none)$ ]] || fail "background must be auto, glassy, or none"
  commit "$NORMALIZE | .dock.background = \$background | del(.dock.backdrop)" --arg background "$background"
  sync_glass
  echo "Dock background set to $background"
}

cmd_defaults() {
  (( $# == 0 )) || fail "defaults does not take arguments"
  commit "$NORMALIZE | .dock = \$defaults[0].dock" --slurpfile defaults "$DEFAULTS_FILE"
  sync_glass
  echo "Dock restored to defaults"
}

command="${1:-}"
(( $# > 0 )) && shift

case "$command" in
  position) cmd_position "$@" ;;
  visibility) cmd_visibility "$@" ;;
  background) cmd_background "$@" ;;
  sync-glass) sync_glass || fail "could not change the blur behind the dock" ;;
  pinned) cmd_pinned "$@" ;;
  pin) cmd_pin "$@" ;;
  unpin) cmd_unpin "$@" ;;
  defaults) cmd_defaults "$@" ;;
  -h | --help | help) usage ;;
  *)
    usage >&2
    exit 1
    ;;
esac
