#!/bin/bash

# omarchy:summary=Toggle the workspace layout, and set every column to one width when it becomes scrolling
# omarchy:args=[width]

set -uo pipefail

# Column width, as a fraction of the screen, applied to every column on the
# workspace when it turns to scrolling.
WIDTH="${1:-0.75}"

hypr_dispatch() {
  local lua="$1"
  shift

  hyprctl dispatch "$lua" >/dev/null 2>&1 || hyprctl dispatch "$@" >/dev/null
}

current_layout() {
  hyprctl activeworkspace -j 2>/dev/null | jq -r '.tiledLayout // empty'
}

omarchy-hyprland-workspace-layout-toggle || exit 1

# The toggle writes a workspace rule, so the new layout can take a moment to
# show up. Read until it does, then act only on the scrolling case: dwindle
# re-tiles on its own and needs no widths.
for _ in {1..6}; do
  case "$(current_layout)" in
  scrolling)
    MSG="colresize all $WIDTH"
    hypr_dispatch "hl.dsp.layout(\"$MSG\")" layoutmsg "$MSG"
    exit 0
    ;;
  dwindle)
    exit 0
    ;;
  esac

  sleep 0.05
done
