#!/bin/bash
# kioskvis - Kiosk Visibility Management Tool
# Manage roomset visibility and eternal users for ISA kiosk mode via visibleRoomsets.json
#
# Usage:
#   kioskvis ls                    - List all roomsets with their visibility status
#   kioskvis enable <id>           - Enable visibility for a roomset (by openapi_id or isacore_id)
#   kioskvis disable <id>          - Disable visibility for a roomset
#   kioskvis users                 - List eternal users
#   kioskvis add-user <username>   - Add an eternal user
#   kioskvis del-user <username>   - Delete an eternal user
#   kioskvis show                  - Show the raw JSON configuration
#   kioskvis path                  - Show the configuration file path

set -e

# Determine config file path (same logic as Flutter app)
if [ -n "$HOME" ]; then
    CONFIG_FILE="$HOME/visibleRoomsets.json"
else
    CONFIG_FILE="/root/visibleRoomsets.json"
fi

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Check if jq is installed
if ! command -v jq &> /dev/null; then
    echo -e "${RED}Error: jq is required but not installed.${NC}"
    echo "Install it with: apt-get install jq"
    exit 1
fi

# Function to display usage
usage() {
    cat << EOF
kioskvis - Kiosk Visibility Management Tool

Usage:
  kioskvis ls                    List all roomsets with visibility status
  kioskvis enable <id>           Enable visibility for a roomset
  kioskvis disable <id>          Disable visibility for a roomset
  kioskvis users                 List eternal users
  kioskvis add-user <username>   Add an eternal user
  kioskvis del-user <username>   Delete an eternal user
  kioskvis show                  Show raw JSON configuration
  kioskvis path                  Show configuration file path
  kioskvis help                  Show this help message

Arguments:
  <id>         Can be either openapi_id or isacore_id of the roomset
  <username>   Email or username for eternal user

Examples:
  kioskvis ls
  kioskvis enable 63bc00f4bcfb27edf14ae5be
  kioskvis disable f8d3e4a2-1b2c-4d5e-9f8a-7b6c5d4e3f2a
  kioskvis users
  kioskvis add-user user@example.com
  kioskvis del-user user@example.com

Configuration file: $CONFIG_FILE
EOF
}

# Function to check if config file exists
check_config() {
    if [ ! -f "$CONFIG_FILE" ]; then
        echo -e "${RED}Error: Configuration file not found: $CONFIG_FILE${NC}"
        echo "The file will be created automatically by the kiosk application on first run."
        exit 1
    fi
}

# Function to list all roomsets
cmd_ls() {
    check_config

    echo -e "${BLUE}Organization:${NC} $(jq -r '.organizationLabel // "Unknown"' "$CONFIG_FILE")"
    echo -e "${BLUE}Last Updated:${NC} $(jq -r '.lastUpdated // "Unknown"' "$CONFIG_FILE")"
    echo ""
    echo -e "${BLUE}Roomsets:${NC}"
    echo "─────────────────────────────────────────────────────────────────────────────"

    jq -r '.roomsets[] |
        "\(.visible)|\(.label)|\(.openapi_id // "null")|\(.isacore_id // "null")"' "$CONFIG_FILE" | \
    while IFS='|' read -r visible label openapi_id isacore_id; do
        if [ "$visible" = "true" ]; then
            status="${GREEN}✓ VISIBLE${NC}"
        else
            status="${RED}✗ HIDDEN${NC}"
        fi

        echo -e "$status  ${YELLOW}$label${NC}"
        echo "          OpenAPI: $openapi_id"
        echo "          IsaCore: $isacore_id"
        echo ""
    done
}

# Function to enable/disable a roomset
cmd_set_visibility() {
    local id="$1"
    local new_visibility="$2"

    check_config

    if [ -z "$id" ]; then
        echo -e "${RED}Error: No ID provided${NC}"
        echo "Usage: kioskvis enable|disable <id>"
        exit 1
    fi

    # Check if ID exists and update visibility
    local updated=false
    local label=""

    # Use jq to update the visibility
    local temp_file=$(mktemp)
    jq --arg id "$id" --argjson vis "$new_visibility" '
        .roomsets |= map(
            if (.openapi_id == $id or .isacore_id == $id) then
                .visible = $vis
            else
                .
            end
        ) |
        .lastUpdated = (now | strftime("%Y-%m-%dT%H:%M:%S.000Z"))
    ' "$CONFIG_FILE" > "$temp_file"

    # Check if any change was made
    label=$(jq -r --arg id "$id" '.roomsets[] | select(.openapi_id == $id or .isacore_id == $id) | .label' "$temp_file")

    if [ -z "$label" ]; then
        echo -e "${RED}Error: No roomset found with ID: $id${NC}"
        echo "Use 'kioskvis ls' to see all available roomsets"
        rm "$temp_file"
        exit 1
    fi

    # Move temp file to actual config
    mv "$temp_file" "$CONFIG_FILE"

    if [ "$new_visibility" = "true" ]; then
        echo -e "${GREEN}✓ Enabled visibility for: $label${NC}"
    else
        echo -e "${YELLOW}✗ Disabled visibility for: $label${NC}"
    fi

    echo "Configuration updated: $CONFIG_FILE"
}

# Function to show raw JSON
cmd_show() {
    check_config
    jq '.' "$CONFIG_FILE"
}

# Function to show config path
cmd_path() {
    echo "$CONFIG_FILE"
    if [ -f "$CONFIG_FILE" ]; then
        echo -e "${GREEN}File exists${NC}"
    else
        echo -e "${RED}File does not exist${NC}"
    fi
}

# Function to list eternal users
cmd_users() {
    check_config

    echo -e "${BLUE}Eternal Users:${NC}"
    echo "─────────────────────────────────────────────────────────────────────────────"

    # Check if eternalUsers array exists
    local users_count=$(jq -r '.eternalUsers // [] | length' "$CONFIG_FILE")

    if [ "$users_count" -eq 0 ]; then
        echo -e "${YELLOW}No eternal users configured${NC}"
        return
    fi

    jq -r '.eternalUsers[] // empty' "$CONFIG_FILE" | while read -r user; do
        echo -e "${GREEN}✓${NC} $user"
    done

    echo ""
    echo -e "${BLUE}Total:${NC} $users_count user(s)"
}

# Function to add an eternal user
cmd_add_user() {
    local username="$1"

    check_config

    if [ -z "$username" ]; then
        echo -e "${RED}Error: No username provided${NC}"
        echo "Usage: kioskvis add-user <username>"
        exit 1
    fi

    # Check if user already exists
    local exists=$(jq -r --arg user "$username" '.eternalUsers // [] | contains([$user])' "$CONFIG_FILE")

    if [ "$exists" = "true" ]; then
        echo -e "${YELLOW}User already exists: $username${NC}"
        exit 0
    fi

    # Add user to eternalUsers array
    local temp_file=$(mktemp)
    jq --arg user "$username" '
        .eternalUsers = (.eternalUsers // []) + [$user] |
        .lastUpdated = (now | strftime("%Y-%m-%dT%H:%M:%S.000Z"))
    ' "$CONFIG_FILE" > "$temp_file"

    # Move temp file to actual config
    mv "$temp_file" "$CONFIG_FILE"

    echo -e "${GREEN}✓ Added eternal user: $username${NC}"
    echo "Configuration updated: $CONFIG_FILE"
}

# Function to delete an eternal user
cmd_del_user() {
    local username="$1"

    check_config

    if [ -z "$username" ]; then
        echo -e "${RED}Error: No username provided${NC}"
        echo "Usage: kioskvis del-user <username>"
        exit 1
    fi

    # Check if user exists
    local exists=$(jq -r --arg user "$username" '.eternalUsers // [] | contains([$user])' "$CONFIG_FILE")

    if [ "$exists" = "false" ]; then
        echo -e "${RED}Error: User not found: $username${NC}"
        echo "Use 'kioskvis users' to see all eternal users"
        exit 1
    fi

    # Remove user from eternalUsers array
    local temp_file=$(mktemp)
    jq --arg user "$username" '
        .eternalUsers = (.eternalUsers // [] | map(select(. != $user))) |
        .lastUpdated = (now | strftime("%Y-%m-%dT%H:%M:%S.000Z"))
    ' "$CONFIG_FILE" > "$temp_file"

    # Move temp file to actual config
    mv "$temp_file" "$CONFIG_FILE"

    echo -e "${YELLOW}✗ Removed eternal user: $username${NC}"
    echo "Configuration updated: $CONFIG_FILE"
}

# Main command dispatcher
case "${1:-}" in
    ls|list)
        cmd_ls
        ;;
    enable)
        cmd_set_visibility "$2" "true"
        ;;
    disable)
        cmd_set_visibility "$2" "false"
        ;;
    users)
        cmd_users
        ;;
    add-user)
        cmd_add_user "$2"
        ;;
    del-user)
        cmd_del_user "$2"
        ;;
    show)
        cmd_show
        ;;
    path)
        cmd_path
        ;;
    help|--help|-h)
        usage
        ;;
    "")
        usage
        exit 1
        ;;
    *)
        echo -e "${RED}Error: Unknown command: $1${NC}"
        echo ""
        usage
        exit 1
        ;;
esac
