Functions/Public/Show-OrionUtilsDemo.ps1

function Show-OrionUtilsDemo {
    <#
    .SYNOPSIS
        Demonstrates all functions in the OrionUtils module.
 
    .DESCRIPTION
        Runs an interactive demo showcasing each function in OrionUtils.
        Useful for learning the module capabilities or verifying installation.
 
    .PARAMETER Category
        Run demo for a specific category only:
        - All (default): Run all demos
        - FileManagement: Remove-StaleFile, Test-FileLock
        - TimeDate: Format-TimeSpan, Get-TimeElapsed
        - Stopwatch: Start-Stopwatch, Stop-Stopwatch, Get-Stopwatch, Reset-Stopwatch, Show-StopwatchSummary
        - UserInteraction: Wait-ForInput
        - Logging: Write-Log, Export-MetricsToCSV
        - System: Get-WindowsVersion
 
    .PARAMETER Pause
        Pause between each demo section for review.
 
    .EXAMPLE
        Show-OrionUtilsDemo
        # Runs the complete demo
 
    .EXAMPLE
        Show-OrionUtilsDemo -Category Stopwatch
        # Demos only the Stopwatch functions
 
    .EXAMPLE
        Show-OrionUtilsDemo -Pause
        # Pauses between each section
 
    .NOTES
        Author: Sune Alexandersen Narud
        Version: 1.0.0
        Date: February 2026
    #>


    [CmdletBinding()]
    param(
        [Parameter()]
        [ValidateSet('All', 'FileManagement', 'TimeDate', 'Stopwatch', 'UserInteraction', 'Logging', 'System')]
        [string]$Category = 'All',

        [Parameter()]
        [switch]$Pause
    )

    #region Helper Functions
    function Write-DemoHeader {
        param([string]$Title)
        Write-Host ""
        Write-Host " ╔════════════════════════════════════════════════════════════════╗" -ForegroundColor Cyan
        Write-Host " ║ " -ForegroundColor Cyan -NoNewline
        Write-Host "$($Title.PadRight(63))" -ForegroundColor White -NoNewline
        Write-Host "║" -ForegroundColor Cyan
        Write-Host " ╚════════════════════════════════════════════════════════════════╝" -ForegroundColor Cyan
        Write-Host ""
    }

    function Write-DemoSection {
        param([string]$FunctionName, [string]$Description)
        Write-Host ""
        Write-Host " ─────────────────────────────────────────────────────────────────" -ForegroundColor DarkGray
        Write-Host " $FunctionName" -ForegroundColor Yellow
        Write-Host " $Description" -ForegroundColor DarkGray
        Write-Host " ─────────────────────────────────────────────────────────────────" -ForegroundColor DarkGray
        Write-Host ""
    }

    function Write-DemoCode {
        param([string]$Code)
        Write-Host " PS> " -ForegroundColor DarkGreen -NoNewline
        Write-Host "$Code" -ForegroundColor Green
    }

    function Write-DemoOutput {
        param([string]$Label, $Value)
        Write-Host " $Label : " -ForegroundColor DarkGray -NoNewline
        Write-Host "$Value" -ForegroundColor White
    }

    function Invoke-DemoPause {
        if ($Pause) {
            Write-Host ""
            Write-Host " Press any key to continue..." -ForegroundColor DarkYellow
            $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
        }
    }
    #endregion

    # Module Header
    $boxWidth = 64
    $title = "ORION UTILS - MODULE DEMO"
    $version = "Version 1.3.0"
    $titlePadded = $title.PadLeft(([math]::Floor($boxWidth / 2) + [math]::Floor($title.Length / 2))).PadRight($boxWidth)
    $versionPadded = $version.PadLeft(([math]::Floor($boxWidth / 2) + [math]::Floor($version.Length / 2))).PadRight($boxWidth)
    $emptyLine = " " * $boxWidth
    $borderLine = "═" * $boxWidth

    Write-Host ""
    Write-Host " ╔$borderLine╗" -ForegroundColor DarkCyan
    Write-Host " ║$emptyLine║" -ForegroundColor DarkCyan
    Write-Host " ║" -ForegroundColor DarkCyan -NoNewline
    Write-Host "$titlePadded" -ForegroundColor Cyan -NoNewline
    Write-Host "║" -ForegroundColor DarkCyan
    Write-Host " ║" -ForegroundColor DarkCyan -NoNewline
    Write-Host "$versionPadded" -ForegroundColor DarkGray -NoNewline
    Write-Host "║" -ForegroundColor DarkCyan
    Write-Host " ║$emptyLine║" -ForegroundColor DarkCyan
    Write-Host " ╚$borderLine╝" -ForegroundColor DarkCyan
    Write-Host ""

    #region Time & Date Demo
    if ($Category -in 'All', 'TimeDate') {
        Write-DemoHeader "TIME & DATE FUNCTIONS"

        # Format-TimeSpan
        Write-DemoSection "Format-TimeSpan" "Formats a TimeSpan into human-readable text"
        
        Write-DemoCode "Format-TimeSpan -TimeSpan ([TimeSpan]::FromMinutes(90))"
        $result = Format-TimeSpan -TimeSpan ([TimeSpan]::FromMinutes(90))
        Write-DemoOutput "Result" $result

        Write-DemoCode "Format-TimeSpan -TimeSpan ([TimeSpan]::FromSeconds(3725)) -Precision Full"
        $result = Format-TimeSpan -TimeSpan ([TimeSpan]::FromSeconds(3725)) -Precision Full
        Write-DemoOutput "Result" $result

        Write-DemoCode "[TimeSpan]::FromDays(2.5) | Format-TimeSpan -Compact"
        $result = [TimeSpan]::FromDays(2.5) | Format-TimeSpan -Compact
        Write-DemoOutput "Result" $result

        # Get-TimeElapsed
        Write-DemoSection "Get-TimeElapsed" "Calculates time elapsed since a given date"

        Write-DemoCode "Get-TimeElapsed -DateTime (Get-Date).AddDays(-5)"
        $result = Get-TimeElapsed -DateTime (Get-Date).AddDays(-5)
        Write-DemoOutput "Result" $result

        Write-DemoCode "Get-TimeElapsed -DateTime (Get-Date).AddHours(-3) -OutputFormat Verbose"
        $result = Get-TimeElapsed -DateTime (Get-Date).AddHours(-3) -OutputFormat Verbose
        Write-DemoOutput "Result" $result

        Write-DemoCode "Get-TimeElapsed -DateTime (Get-Date).AddDays(-10) -OutputFormat Days"
        $result = Get-TimeElapsed -DateTime (Get-Date).AddDays(-10) -OutputFormat Days
        Write-DemoOutput "Result" "$result days"

        Invoke-DemoPause
    }
    #endregion

    #region Stopwatch Demo
    if ($Category -in 'All', 'Stopwatch') {
        Write-DemoHeader "STOPWATCH / PERFORMANCE TIMING"

        Write-DemoSection "Start-Stopwatch / Stop-Stopwatch" "Time code execution with named stopwatches"

        # Clear any existing stopwatches
        Reset-Stopwatch -ErrorAction SilentlyContinue

        Write-DemoCode "Start-Stopwatch -Name 'Database Query' -ShowStart"
        Start-Stopwatch -Name 'Database Query' -ShowStart
        Start-Sleep -Milliseconds 500

        Write-DemoCode "Start-Sleep -Milliseconds 500 # Simulating work..."
        Write-DemoCode "Stop-Stopwatch -Name 'Database Query' -ShowElapsed"
        Stop-Stopwatch -Name 'Database Query' -ShowElapsed

        Write-DemoCode "Start-Stopwatch -Name 'File Processing'"
        Start-Stopwatch -Name 'File Processing'
        Start-Sleep -Milliseconds 300
        Write-DemoCode "Stop-Stopwatch -Name 'File Processing'"
        Stop-Stopwatch -Name 'File Processing'

        Write-DemoCode "Start-Stopwatch -Name 'API Call'"
        Start-Stopwatch -Name 'API Call'
        Start-Sleep -Milliseconds 750
        Write-DemoCode "Stop-Stopwatch -Name 'API Call'"
        Stop-Stopwatch -Name 'API Call'

        # Get-Stopwatch
        Write-DemoSection "Get-Stopwatch" "Retrieve stopwatch data programmatically"

        Write-DemoCode "Get-Stopwatch | Select-Object Name, TotalSeconds"
        Get-Stopwatch | Select-Object Name, @{N='Seconds';E={[math]::Round($_.TotalSeconds, 2)}} | ForEach-Object {
            Write-DemoOutput $_.Name "$($_.Seconds) sec"
        }

        # Show-StopwatchSummary
        Write-DemoSection "Show-StopwatchSummary" "Display formatted performance summary"

        Write-DemoCode "Show-StopwatchSummary -Title 'Demo Performance Results'"
        Show-StopwatchSummary -Title 'Demo Performance Results'

        # Reset-Stopwatch
        Write-DemoSection "Reset-Stopwatch" "Clear stopwatch data"

        Write-DemoCode "Reset-Stopwatch"
        Reset-Stopwatch
        Write-Host " Stopwatch data cleared." -ForegroundColor DarkGray

        Invoke-DemoPause
    }
    #endregion

    #region File Management Demo
    if ($Category -in 'All', 'FileManagement') {
        Write-DemoHeader "FILE MANAGEMENT FUNCTIONS"

        # Test-FileLock
        Write-DemoSection "Test-FileLock" "Check if a file is locked by another process"

        $testFile = $env:TEMP + "\orion-demo-test.txt"
        "Demo content" | Set-Content $testFile -Force

        Write-DemoCode "Test-FileLock -FilePath '$testFile'"
        $result = Test-FileLock -FilePath $testFile
        Write-DemoOutput "Is Locked" $result

        Write-DemoCode "Test-FileLock -FilePath '$testFile' -Silent"
        $result = Test-FileLock -FilePath $testFile -Silent
        Write-DemoOutput "Is Locked (Silent)" $result

        Remove-Item $testFile -Force -ErrorAction SilentlyContinue

        # Remove-StaleFile
        Write-DemoSection "Remove-StaleFile" "Keep N newest files, remove the rest"

        # Create demo files
        $demoPath = Join-Path $env:TEMP "OrionDemo"
        New-Item -Path $demoPath -ItemType Directory -Force | Out-Null
        1..5 | ForEach-Object {
            $file = Join-Path $demoPath "log_$_.txt"
            "Log content $_" | Set-Content $file
            Start-Sleep -Milliseconds 50  # Ensure different timestamps
        }

        Write-DemoCode "Get-ChildItem '$demoPath' | Select-Object Name"
        Get-ChildItem $demoPath | ForEach-Object { Write-DemoOutput "File" $_.Name }

        Write-DemoCode "Remove-StaleFile -Path '$demoPath' -Filter '*.txt' -Keep 2 -WhatIf"
        Write-Host ""
        Remove-StaleFile -Path $demoPath -Filter '*.txt' -Keep 2 -WhatIf

        # Cleanup
        Remove-Item $demoPath -Recurse -Force -ErrorAction SilentlyContinue

        Invoke-DemoPause
    }
    #endregion

    #region User Interaction Demo
    if ($Category -in 'All', 'UserInteraction') {
        Write-DemoHeader "USER INTERACTION FUNCTIONS"

        # Wait-ForInput - Timer mode
        Write-DemoSection "Wait-ForInput -Timer" "Countdown timer with key press interruption"

        Write-DemoCode "Wait-ForInput -Timer 3 -ShowCountdown -Message 'Waiting {0} seconds...'"
        Write-Host " (Press any key to skip or wait 3 seconds)" -ForegroundColor DarkGray
        Wait-ForInput -Timer 3 -ShowCountdown -Message 'Waiting {0} seconds...'

        # Wait-ForInput - Immediate mode
        Write-DemoSection "Wait-ForInput" "Simple 'press any key' prompt"

        Write-DemoCode "Wait-ForInput -Message 'Demo paused. Press any key...'"
        Wait-ForInput -Message 'Demo paused. Press any key...'

        Invoke-DemoPause
    }
    #endregion

    #region Logging Demo
    if ($Category -in 'All', 'Logging') {
        Write-DemoHeader "LOGGING & METRICS FUNCTIONS"

        # Write-Log
        Write-DemoSection "Write-Log" "Structured logging to file"

        $logFile = Join-Path $env:TEMP "orion-demo.log"

        Write-DemoCode "Write-Log -Message 'Application started' -Level INFO -LogFile '$logFile'"
        Write-Log -Message 'Application started' -Level INFO -LogFile $logFile

        Write-DemoCode "Write-Log -Message 'Processing data...' -Level DEBUG -LogFile '$logFile'"
        Write-Log -Message 'Processing data...' -Level DEBUG -LogFile $logFile

        Write-DemoCode "Write-Log -Message 'Operation completed' -Level SUCCESS -LogFile '$logFile'"
        Write-Log -Message 'Operation completed' -Level SUCCESS -LogFile $logFile

        Write-Host ""
        Write-Host " Log file contents:" -ForegroundColor DarkGray
        Get-Content $logFile | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }

        Remove-Item $logFile -Force -ErrorAction SilentlyContinue

        # Export-MetricsToCSV
        Write-DemoSection "Export-MetricsToCSV" "Export metrics to CSV with timestamp"

        $metrics = [PSCustomObject]@{
            Server      = 'SRV01'
            CPU         = 45.2
            Memory      = 8192
            Connections = 150
        }

        $csvFile = Join-Path $env:TEMP "orion-metrics.csv"

        Write-DemoCode '$metrics = [PSCustomObject]@{ Server="SRV01"; CPU=45.2; Memory=8192 }'
        Write-DemoCode "Export-MetricsToCSV -Metrics `$metrics -Path '$csvFile'"
        Export-MetricsToCSV -Metrics $metrics -Path $csvFile

        Write-Host ""
        Write-Host " CSV file contents:" -ForegroundColor DarkGray
        Get-Content $csvFile | ForEach-Object { Write-Host " $_" -ForegroundColor Gray }

        Remove-Item $csvFile -Force -ErrorAction SilentlyContinue

        Invoke-DemoPause
    }
    #endregion

    #region System Demo
    if ($Category -in 'All', 'System') {
        Write-DemoHeader "SYSTEM UTILITY FUNCTIONS"

        # Get-WindowsVersion
        Write-DemoSection "Get-WindowsVersion" "Convert OS build number to friendly name"

        Write-DemoCode "Get-WindowsVersion -OSVersion '10.0.22631'"
        $result = Get-WindowsVersion -OSVersion '10.0.22631'
        Write-DemoOutput "Result" $result

        Write-DemoCode "Get-WindowsVersion -OSVersion '10.0.19045'"
        $result = Get-WindowsVersion -OSVersion '10.0.19045'
        Write-DemoOutput "Result" $result

        Write-DemoCode "Get-WindowsVersion -OSVersion '10.0.26100'"
        $result = Get-WindowsVersion -OSVersion '10.0.26100'
        Write-DemoOutput "Result" $result

        Invoke-DemoPause
    }
    #endregion

    # Footer
    Write-Host ""
    Write-Host " ════════════════════════════════════════════════════════════════" -ForegroundColor DarkCyan
    Write-Host " Demo Complete! " -ForegroundColor Green -NoNewline
    Write-Host "For help on any function, use: " -ForegroundColor Gray -NoNewline
    Write-Host "Get-Help <FunctionName>" -ForegroundColor Yellow
    Write-Host " ════════════════════════════════════════════════════════════════" -ForegroundColor DarkCyan
    Write-Host ""
}