#!/usr/bin/env bash
# commands/group/list.sh

function cmd::group::list::on_load() {
  command::mixin json_output section:Output
}

function cmd::group::list::run() {
  flag::parse "$@" || return 1

  local groups_dir; groups_dir="$(ctx::groups)"
  local groups=("${groups_dir}"/*.group)
  if [[ ! -f "${groups[0]}" ]]; then
    log::wg "No groups configured"; return 0
  fi

  if command::json; then
    cmd::group::_output_json; return 0
  fi

  local data
  data=$(json::group_list_data "$groups_dir" "$(ctx::blocks)" "$(ctx::clients)")
  [[ -z "$data" ]] && log::wg "No groups configured" && return 0

  local w_name=12 w_desc=16
  while IFS="|" read -r name desc total blocked; do
    [[ -z "$name" ]] && continue
    (( ${#name} > w_name )) && w_name=${#name}
    local desc_len=${#desc}; [[ -z "$desc" ]] && desc_len=1
    (( desc_len > w_desc )) && w_desc=$desc_len
  done <<< "$data"
  (( w_name += 2 )); (( w_desc += 2 ))

  log::section "Groups"; echo ""

  if display::is_table "group_list"; then
    cmd::group::_render_table "$data" "$w_name" "$w_desc"
    return 0
  fi

  while IFS="|" read -r name desc total blocked; do
    [[ -z "$name" ]] && continue
    ui::group::list_row "$name" "$desc" "$total" "$blocked" "$w_name" "$w_desc"
  done <<< "$data"
  echo ""
}
