#!/bin/zsh
source $HOME/.config/sway/bin/sway_helpers
CMD=$HOME/.config/sway/bin/sway_output
# BAT_PATH=/sys/class/power_supply
# BAT=BAT0
# MODE=suspend-then-hibernate

## helpers
function _get() {
  _check_app jq
  data=()
  swaymsg -t get_outputs | jq -r ".[] | .$1" | while read line; do
    line=${line:gs/ /_}
    data+=($line)
  done
  echo $data
}

function _outputs() {
  make=( $(_get make) )
  model=( $(_get model) )
  serial=( $(_get serial) )
  name=( $(_get name) )
  active=( $(_get active) )
  for i in $(seq ${#make[@]}); do
    ac=${active[$i]/true/active}
    ac=${ac/false/inactive}
    printf "  - %2d %6s %10s %20s %15s %10s\n" $i ${name[$i]} "($ac)" ${make[$i]} ${model[$i]} ${serial[$i]}
  done
}

function _enable() {
  n=( $(_get name) )
  swaymsg output ${n[$1]} enable
}

function _disable() {
  n=( $(_get name) )
  swaymsg output ${n[$1]} disable
}

function _interactive() {
  echo "outputs (any key to abort)"
  _outputs
  num=$(_outputs | wc -l)

  read -k 1 "o?select output: "
  if [ $o -le $num ]; then
    echo ""
  echo ""
  else
    echo "error: invalid output selected: $o"
    return 1
  fi

  echo "actions (any key to abort)"
  printf "  - %2s %6s\n" "1" "enable"
  printf "  - %2s %6s\n" "2" "disable"
  read -k 1 "a?select action: "
  if [ $a -le 2 ]; then
    echo ""
    echo ""
    case $a in
      1)
        echo "enabling $o"
        _enable $o
        ;;
      2)
        echo "disabling $o"
        _disable $o
        ;;
    esac
  else
    echo "error: invalid action selected $a"
    return 1
  fi
}

# generate enab
function _nag() {
  _check_app swaynag
  name=( $(_get name) )
  z=()
  # for n in $name; do
  #   z+=" -z \"enable $n\" \"$CMD enable $n\""
  #   z+=" -z \"disable $n\" \"$CMD disable $n\""
  # done

  # swaynag -m "control outputs" $(echo ${z[@]})
  # swaynag -m "control outputs" $(echo ${z})
}

## main
# _log OUTPUTS INFO args: $*

case $1 in
  o*)
    echo "outputs: "
    _outputs
    ;;
  e*)
    _enable $2
    ;;
  d*)
    _disable $2
    ;;
  n*)
    _nag
    ;;
  -h|--help|help)
    echo "invalid argument: \"$1\""
    echo "arguments: [outputs|enable #|disable #]"
    ;;
  *)
    _interactive
    ;;
esac
