#!/bin/bash

# Update a specific app's status in apps.json (used for install/uninstall operations)
webuiUpdateAppStatus() {
    local app_name="$1"
    local output_file="${containers_dir}libreportal/frontend/data/apps/generated/apps.json"
    
    if [[ -z "$app_name" ]]; then
        isError "app_name parameter required for webuiUpdateAppStatus"
    fi
    
    if [[ ! -f "$output_file" ]]; then
        isNotice "WebUI apps.json file not found. Skipping..."
    else
        # Check if app is installed
        local is_installed=false
        if [ -d "${containers_dir}${app_name}" ]; then
            is_installed=true
        fi
        
        # Create temporary file for the updated JSON
        local temp_file=$(mktemp)
        
        # Process the JSON file and update the specific app's installed status
        local found_app=false
        local in_target_app=false
        
        while IFS= read -r line; do
            if [[ "$line" =~ \"command\":\ \"libreportal\ app\ install\ $app_name\" ]]; then
                in_target_app=true
                found_app=true
                echo "$line" >> "$temp_file"
            elif [[ "$in_target_app" == true && "$line" =~ \"installed\":\ (true|false) ]]; then
                # Replace the installed status
                echo "      \"installed\": $is_installed," >> "$temp_file"
                in_target_app=false
            else
                echo "$line" >> "$temp_file"
            fi
        done < "$output_file"
        
        # Replace the original file with the updated one
        runFileWrite "$output_file" < "$temp_file"; rm -f "$temp_file"
        
        if [[ "$found_app" == true ]]; then
            isSuccessful "Updated $app_name status to: $is_installed"
        else
            isNotice "Warning: App $app_name not found in apps.json"
        fi

        isSuccessful "Updating status for $app_name in apps.json..."
    fi
}
