#!/usr/bin/env bash

# ============================================
# Flag Registry
# ============================================

declare -A _REGISTERED_FLAGS=()

# ============================================
# Registration
# ============================================

function flag::register() {
  local flag="$1"
  _REGISTERED_FLAGS["$flag"]=1
}

function flag::registered() {
  [[ -n "${_REGISTERED_FLAGS["$1"]:-}" ]]
}

# ============================================
# Parsing
# ============================================

# Parse flags from args into associative array
# Usage: flag::parse "$@"
# Access: flag::get --name
declare -A _FLAG_VALUES=()

function flag::parse() {
  _FLAG_VALUES=()

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --*)
        local key="$1"
        # Boolean flag (no value follows, or next arg is another flag)
        if [[ $# -eq 1 || "$2" == --* ]]; then
          _FLAG_VALUES["$key"]="true"
          shift
        else
          _FLAG_VALUES["$key"]="$2"
          shift 2
        fi
        ;;
      *)
        shift
        ;;
    esac
  done
}

function flag::get() {
  echo "${_FLAG_VALUES["$1"]:-}"
}

function flag::enabled() {
  [[ "${_FLAG_VALUES["$1"]:-}" == "true" ]]
}

function flag::set() {
  local key="$1"
  local value="$2"
  _FLAG_VALUES["$key"]="$value"
}
