devTraceHelper.psm1

function out  {
    param(
        $varValue,
        [string]$varName,
        [switch] $asGrid,
        [switch] $compactJSON
    )

    if ($asGrid){
        showTable($varValue)
        Write-Host  "Grid form is called here `t<< `t("-ForegroundColor DarkGray -NoNewline
        Write-Host  ([string]$(Get-PSCallStack)[1]).split('\')[-1] -ForegroundColor DarkGreen -NoNewline
        Write-Host  ")"-ForegroundColor DarkGray
    }else{
        if($compactJSON){
            $val = $varValue | ConvertTo-Json -Compress
        }else{
            $val = $varValue | ConvertTo-Json
        }
        

        Write-Host ":" -ForegroundColor Red -NoNewline
        Write-Host $varName -ForegroundColor DarkGray -NoNewline
        Write-Host ": " -ForegroundColor Red -NoNewline
        Write-Host $val -ForegroundColor DarkBlue  -NoNewline

        Write-Host  " `t<< `t("-ForegroundColor DarkGray -NoNewline
        Write-Host  ([string]$(Get-PSCallStack)[1]).split('\')[-1] -ForegroundColor DarkGreen -NoNewline
        Write-Host  ")"-ForegroundColor DarkGray
    }
}

function startMeasureTime() {
    $script:stopWatch = [System.Diagnostics.Stopwatch]::startNew()    
}

function stopMeasureTime($msg) {
    $stopWatch.Stop()
    if (!$msg) {
        $msg = 'It took'
    }
    Write-Host " === $msg $($stopWatch.ElapsedMilliseconds) milliseconds === " -ForegroundColor Yellow 
}

function showTable($result) {
    Start-Process PowerShell -WindowStyle hidden -argument "-command $($result | Out-GridView)"

    if (!$Global:isGridForeGround) {
        setForegroundWindow("*Start-Process PowerShell*")
        sendKeysAltShiftTab
        $Global:isGridForeGround = $true
    }
    
    
}

function sendKeysAltShiftTab() {
    [void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
    # SHIFT +
    # CTRL ^
    # ALT %
    [System.Windows.Forms.SendKeys]::SendWait("%+{TAB}") 
}

function setForegroundWindow($name) {
    $p = Get-Process | Where { $_.mainWindowTitle -like $name } 
    if (!$p) {
        out 'No process found!'
        return
    }
    $h = $p.MainWindowHandle
    Add-Type @"
    using System;
    using System.Runtime.InteropServices;
    public class WinAp {
      [DllImport("user32.dll")]
      [return: MarshalAs(UnmanagedType.Bool)]
      public static extern bool SetForegroundWindow(IntPtr hWnd);
 
      [DllImport("user32.dll")]
      [return: MarshalAs(UnmanagedType.Bool)]
      public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    }
"@

    [void] [WinAp]::SetForegroundWindow($h)
    # [void] [WinAp]::ShowWindow($h, 3)
}

Export-ModuleMember out
Export-ModuleMember startMeasureTime
Export-ModuleMember stopMeasureTime