#!/bin/bash

viewAppConfigs() 
{
    while true; do
        isHeader "Installed Applications"
        
        # Get all installed apps from containers directory
        local installed_apps=()
        for app_dir in "$containers_dir"/*/; do
            if [ -d "$app_dir" ]; then
                local app_name=$(basename "$app_dir")
                installed_apps+=("$app_name")
            fi
        done
        
        if [ ${#installed_apps[@]} -eq 0 ]; then
            isNotice "No installed applications found."
        fi
        
        # Display all installed apps with numbers
        for ((i = 0; i < ${#installed_apps[@]}; i++)); do
            local app_name="${installed_apps[i]}"
            isOption "$((i + 1)). $app_name"
        done
        
        echo ""
        isOption "x. Exit"
        echo ""
        isQuestion "Enter app number to configure (or x to exit): "
        read -p "" selected_app_number
        
        if [[ "$selected_app_number" == "x" ]]; then
            if [[ $config_edited == "true" ]]; then
                echo ""
                isNotice "Reloading configuration file(s) for Applications."
                echo ""
                sourceScanFiles "app_configs"
            else
                isNotice "Exiting..."
                echo ""
                checkConfigFilesMissingVariables true
                crontabSetupBackupScheduler
            fi
        elif [[ "$selected_app_number" =~ ^[0-9]+$ ]] && [ "$selected_app_number" -ge 1 ] && [ "$selected_app_number" -le ${#installed_apps[@]} ]; then
            local index=$((selected_app_number - 1))
            local selected_app="${installed_apps[index]}"
            
            # Get the config file for this app
            local config_file="$containers_dir/${selected_app}/${selected_app}.config"
            
            if [ -f "$config_file" ]; then
                $CFG_TEXT_EDITOR "$config_file"
                createTouch "$config_file" $sudo_user_name
                echo ""
                isNotice "Configuration file for '$selected_app' has been updated."
                echo ""
            else
                isNotice "Configuration file for '$selected_app' not found."
                echo ""
            fi
        else
            isNotice "Invalid input. Please enter a valid number or 'x' to exit."
            echo ""
            read -p "Press Enter to continue."
        fi
    done
}
