# ========================================================
# tools.ps1 - Collection of utility functions and global variables
# ========================================================

# --- Global Variables ---
# These variables are initialized once when tools.ps1 is imported
# and are then available throughout the calling script.
$global:objFSO       = New-Object -ComObject Scripting.FileSystemObject # FileSystemObject for file operations (less common in PowerShell)
$global:wshShell     = New-Object -ComObject WScript.Shell             # WScript.Shell for system interaction (less common in PowerShell)
$global:appData      = [Environment]::GetFolderPath("ApplicationData") # APPDATA environment variable path

# Global Constant for not installed status
$global:NOT_INSTALLED = "*** not installed ***"

# --- Console Output Functions ---
# printLN: Prints a line of text and adds a newline character.
# Supports color for better console output.
Function printLN {
    param(
        [string]$Message,
        [ConsoleColor]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color
}

# print: Prints text without adding a newline character.
# Supports color for better console output.
Function print {
    param(
        [string]$Message,
        [ConsoleColor]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color -NoNewline
}

# --- Console Input Function ---
# scanf: Reads a line of user input from the console.
Function scanf {
    Read-Host
}

# --- Program Exit Function ---
# quitPrg: Displays an exit message and terminates the script.
Function quitPrg {
    print "Press ENTER to quit " -NoNewline -Color DarkGray
    [void](scanf) # Discard input
    Exit
}

# --- String Helper Function ---
# padEnd: Pads a string to a minimum length with spaces at the end.
Function padEnd {
    param(
        [string]$Text,
        [int]$Length
    )
    If ($Text.Length -lt $Length) {
        $Text.PadRight($Length)
    } Else {
        $Text
    }
}

# --- WebIQ Specific Functions ---

# getWebIQWorkspaces: Searches APPDATA for WebIQ workspaces and populates an ArrayList.
# Relies on the globally available $global:objFSO and $global:appData.
Function getWebIQWorkspaces {
    param(
        [string]$sAppInfo,                         # The filename (relative path) to identify a WebIQ project.
        [System.Collections.ArrayList]$designerFilesArray # ArrayList to be populated with project root paths.
    )

    $appDataPath = $global:appData

    If (-not (Test-Path $appDataPath -PathType Container)) {
        printLN "WARNING: APPDATA path not found: $appDataPath" -Color Yellow
        return # Exit if AppData path is invalid
    }

    Get-ChildItem -Path $appDataPath -Directory -Recurse -Depth 1 -ErrorAction SilentlyContinue | ForEach-Object {
        $subFolderLevel1 = $_.FullName
        Get-ChildItem -Path $subFolderLevel1 -Directory -Depth 1 -ErrorAction SilentlyContinue | ForEach-Object {
            $subFolderLevel2 = $_.FullName
            $targetFilePath = Join-Path $subFolderLevel2 $sAppInfo
            If (Test-Path $targetFilePath -PathType Leaf) {
                [void]$designerFilesArray.Add($subFolderLevel2)
            }
        }
    }
}

# getProjectName: Reads the project name from the webiq.json file.
Function getProjectName {
    param(
        [string]$sFile # The full path to the webiq.json file.
    )
    If (Test-Path $sFile -PathType Leaf) {
        $jsonContent = Get-Content $sFile -Raw | ConvertFrom-Json -ErrorAction SilentlyContinue
        If ($jsonContent -and $jsonContent.name) {
            return $jsonContent.name
        }
    }
    return "???" # Default value if not found.
}

# getProjectFolder: Reads the application folder name from the app-info.json file.
Function getProjectFolder {
    param(
        [string]$sFile # The full path to the app-info.json file.
    )
    If (Test-Path $sFile -PathType Leaf) {
        $jsonContent = Get-Content $sFile -Raw | ConvertFrom-Json -ErrorAction SilentlyContinue
        If ($jsonContent -and $jsonContent.app_name) {
            return $jsonContent.app_name
        }
    }
    return "???" # Default value if not found.
}

# getAddonVersion: Reads the AddOn version from a version.txt file.
Function getAddonVersion {
    param(
        [string]$sDir # The directory path to the addon folder.
    )
    $sFileVersion = Join-Path $sDir "json\version.txt"
    If (Test-Path $sFileVersion -PathType Leaf) {
        return (Get-Content $sFileVersion -First 1)
    }
    return $global:NOT_INSTALLED # Global constant for "not installed" status.
}

# wait: Pauses script execution for a specified number of seconds.
Function wait {
    param(
        [int]$n # Number of seconds to wait.
    )
    Start-Sleep -Seconds $n
}