Includes/PwSh.Fw.Write.psm1

<#
 
    .SYNOPSIS
    Resource file to export useful functions to prettify output
 
    .DESCRIPTION
 
    .NOTES
        Author: Charles-Antoine Degennes <cadegenn@gmail.com>
        New-ModuleManifest api.psd1 -RootModule api.psm1 -ModuleVersion "0.0.1" -Author "Charles-Antoine Degennes <cadegenn@gmail.com>"
#>


$Script:NS = (get-item $PSCommandPath).basename

# # Error codes enum
# Enum pwshfwERROR {
# OK = 0
# FAILED = 1
# RUNNING = 2
# MISSED = 3
# SKIPPED = 4
# UNUSED = 5
# UNKNOWN = 6
# DEAD = 7
# NOTFOUND = 8
# }

$Script:indent = ""
$Script:prepend = " * "
$Script:titleChar = "*"
$Script:lineBreakChar = "-"

<#
    .SYNOPSIS
    Indent further calls to e*() functions
 
    .DESCRIPTION
    Indent with 2 spaces
 
    .NOTES
        TODO:
            . add parameter to override indent size
#>

function Write-Indent() {
    [CmdletBinding()]param(
        [switch]$PassThru
    )
    $Script:indent += " "
    if ($PassThru) { return $Script:indent }
}

<#
    .SYNOPSIS
    Outdent further calls to e*() functions
 
    .DESCRIPTION
    un-indent for 2 spaces
 
    .NOTES
        TODO:
            . add parameter to override indent size
#>

function Write-Outdent() {
    [CmdletBinding()]param(
        [switch]$PassThru
    )
    if ($Script:indent.Length -gt 3) {
        $Script:indent = $Script:indent.Substring(0,$Script:indent.Length - 3)
    } else {
        $Script:indent = ""
    }
    if ($PassThru) { return $Script:indent }
}

<#
    .SYNOPSIS
    Print a title
 
    .DESCRIPTION
    Print a title in green
 
#>

function Write-Title() {
    [CmdletBinding()]param(
        [string]$message,
        [switch]$PassThru
    )
    $hr = "*" * ($message.Length + $indent.length + 6)
    $message = "** " + $indent + $message + " **"
    Write-ToLogFile -Message $hr
    Write-ToLogFile -Message $message
    if ($PassThru) {
        return $message
    } else {
        Write-Host -ForegroundColor Green "`n`n$hr"
        Write-Host -NoNewline -ForegroundColor Green $message
    }
}

<#
    .SYNOPSIS
    Print a message without new line
 
    .DESCRIPTION
    Print a message without new line
 
     .PARAMETER message
    Text to display on screen
 
     .PARAMETER width
    Optional. Used to pad text to the left.
 
#>

function Write-Begin() {
    [CmdletBinding()]param(
        [string]$message,
        [int32]$width = $Host.UI.RawUI.WindowSize.Width
    )
    $fullMessage = $prepend + $indent + $message + "... "
    #$ht = "." * ($Host.UI.RawUI.WindowSize.Width - $message.Length)
    $width = $width - 16
    Write-Host -NoNewline -ForegroundColor DarkGreen $("`n{0,-$width}" -f $fullMessage)
    Write-ToLogFile -NoNewline -Message $fullMessage
}

<#
    .SYNOPSIS
    Add message to current line.
 
    .DESCRIPTION
    Add text to current line of text. No new line at the beginning, no new line at the end.
 
#>

function Write-Add() {
    [CmdletBinding()]param(
        [string]$message
    )
    Write-Host -NoNewline $Message
    Write-ToLogFile -NoNewline -Message $message
}

<#
    .SYNOPSIS
    Print a message depending on return code
 
    .DESCRIPTION
    Print a message of status code.
    All status MUST have the same length. It is used to properly align all messages
 
#>

function Write-End() {
    [CmdletBinding()]param(
        $errorCode
    )

    if (-not($errorCode)) { $errorCode = $false }
    $color = "White"  ; $message = $errorCode

    switch -wildcard ($errorCode.GetTYpe().Name) {
        "Bool*" {
            switch ($errorCode) {
                $true  { $color = "Green"   ; $message = " ok " }
                $false { $color = "Red"     ; $message = " failed " }
            }
        }
        "Int*" {
            switch ($errorCode) {
                # 0 is never called since `Write-End 0` goes to the bool switch
                # 0 { $color = "Green"; $message = " ok " }
                1    { $color = "Red";        $message = " failed " }
                2    { $color = "DarkGreen"; $message = " running " }
                3    { $color = "Yellow";    $message = " missed " }
                4    { $color = "Gray";        $message = " skipped " }
                5    { $color = "Gray";        $message = " unused " }
                6    { $color = "Gray";        $message = " unknown " }
                7    { $color = "Red";        $message = " dead " }
                8    { $color = "Gray";        $message = "not found" }
            }
        }
        # "pwshfwERROR" {
        # switch ($errorCode) {
        # ([pwshfwERROR]::OK) { $color = "Green"; $message = " ok " }
        # ([pwshfwERROR]::FAILED) { $color = "Red"; $message = " failed " }
        # ([pwshfwERROR]::RUNNING) { $color = "DarkGreen"; $message = " running " }
        # ([pwshfwERROR]::MISSED) { $color = "Yellow"; $message = " missed " }
        # ([pwshfwERROR]::SKIPPED) { $color = "Gray"; $message = " skipped " }
        # ([pwshfwERROR]::UNUSED) { $color = "Gray"; $message = " unused " }
        # ([pwshfwERROR]::UNKNOWN) { $color = "Gray"; $message = " unknown " }
        # ([pwshfwERROR]::DEAD) { $color = "Red"; $message = " dead " }
        # ([pwshfwERROR]::NOTFOUND) { $color = "Gray"; $message = "not found" }
        # default { $color = "White"; $message = $errorCode }
        # }
        # }
    }
    $message = "[ " + $message + " ]"
    Write-Host -NoNewline -ForegroundColor $color $message
    Write-ToLogFile -NoHeader -Message $message
}

<#
    .SYNOPSIS
    Print a message when entering a function
 
    .DESCRIPTION
    Print a message specifically when entering a function.
 
    .EXAMPLE
    # eenter ""
 
#>

function Write-EnterFunction() {
    # [CmdletBinding()]param(
    # [string]$message
    # )
    $callStack = Get-PSCallStack
    if ($callStack.Count -gt 1) {
        $message = $callStack[1].Command
        # $callStack[1] | fl *
    }
    $message = ">> " + $message + "()"
    if ($Global:TRACE) {
        Write-Devel ($message)
        eindent
    }
}

<#
    .SYNOPSIS
    Print a message when leaving a function
 
    .DESCRIPTION
    Print a message specifically when entering a function.
 
    .EXAMPLE
    # eenter ""
 
#>

function Write-LeaveFunction() {
    # [CmdletBinding()]param(
    # [string]$message
    # )
    $callStack = Get-PSCallStack
    if ($callStack.Count -gt 1) {
        $message = $callStack[1].Command
        # $callStack[1] | fl *
    }
    $message = "<< " + $message + "()"
    if ($Global:TRACE) {
        eoutdent
        Write-Devel ($message)
    }
}

<#
    .SYNOPSIS
    Print a message when entering something
 
    .DESCRIPTION
    Print a message and indent output for following messages.
    It is useful when entering a loop, or a module, or an external script.
 
    .EXAMPLE
    # eenter ""
 
#>

function Write-Enter() {
    [CmdletBinding()]param(
        [string]$message
    )
    $message = ">> " + $message + "()"
    Write-Info ($message)
    eindent
}

<#
    .SYNOPSIS
    Print a message when leaving a something
 
    .DESCRIPTION
    Print a message specifically when entering a function.
    It is useful when leaving a loop, or a module, or an external script.
 
    .EXAMPLE
    # eenter ""
 
#>

function Write-Leave() {
    [CmdletBinding()]param(
        [string]$message
    )
    eoutdent
    $message = "<< " + $message + "()"
    Write-Info ($message)
}

<#
    .SYNOPSIS
    Print a devel message
 
    .DESCRIPTION
    Used to print content of command
 
#>

function Write-Devel() {
    [CmdletBinding()]param(
        [string]$message
    )
    if ($Global:DEVEL -eq $false) { return }
    $fullmessage = $prepend + "DEV: " + $indent + $message
    Write-Host -NoNewline -ForegroundColor DarkGray ("`n" + $fullmessage)
    #Write-Debug ($indent + " " + $message)
    Write-ToLogFile -Message $fullmessage
}

<#
    .SYNOPSIS
    Print a debug message
 
    .DESCRIPTION
    Override Write-Debug() powershell function
    Mainly used to print Key = Valu pair
 
#>

function Write-MyDebug() {
    [CmdletBinding()]param(
        [string]$message
    )
    if ($Global:DEBUG -eq $false) { return }
    $fullmessage = $prepend + "DBG: " + $indent + $message
    Write-Host -NoNewline -ForegroundColor Gray ("`n" + $fullmessage)
    #Write-Debug ($indent + " " + $message)
    Write-ToLogFile -Message $fullmessage
}

<#
    .SYNOPSIS
    Print a verbose message
 
    .DESCRIPTION
    Override Write-Verbose() powershell function
 
#>

function Write-MyVerbose() {
    [CmdletBinding()]param(
        [string]$message
    )
    if ($VERBOSE -eq $false) { return }
    $fullmessage = $prepend + $indent + $message
    Write-Host -NoNewline -ForegroundColor White  ("`n" + $fullmessage)
    #Write-Verbose ($indent + " " + $message)
    Write-ToLogFile -Message $fullmessage
}

<#
    .SYNOPSIS
    Print a warning message
 
    .DESCRIPTION
    Override Write-Warning() powershell function
 
#>

function Write-MyWarning() {
    [CmdletBinding()]param(
        [string]$message
    )
    $fullmessage = $prepend + "WRN: " + $indent + $message
    Write-Host -NoNewline -ForegroundColor Yellow ("`n" + $fullmessage)
    Write-ToLogFile -Message $fullmessage
}

<#
    .SYNOPSIS
    Print an error message
 
    .DESCRIPTION
    Override Write-Error() powershell function
 
#>

function Write-MyError() {
    [CmdletBinding()]param(
        [string]$message
    )
    $fullmessage = $prepend + "ERR: " + $indent + $message
    Write-Host -NoNewline -ForegroundColor Red ("`n" + $fullmessage)
    Write-ToLogFile -Message ($fullmessage)
}

<#
    .SYNOPSIS
    Print an information message
 
    .DESCRIPTION
    Override Write-Information() powershell function
 
#>

function Write-Info() {
    [CmdletBinding()]param(
        [string]$message
    )
    $fullmessage = $prepend + $indent + $message
    Write-Host -NoNewline -ForegroundColor Gray ("`n" + $fullmessage)
    Write-ToLogFile -Message ($fullmessage)
}

<#
    .SYNOPSIS
    Print a fatal error message then exist script
 
    .DESCRIPTION
    Print an error message before terminate current script
 
    .EXAMPLE
    Write-Fatal "fatal error. Abort."
 
#>

function Write-Fatal() {
    [CmdletBinding()]param(
        [string]$message
    )
    Write-MyError -ErrorAction:Stop -Message $message
    Throw " Aborting."
}

<#
    .SYNOPSIS
    Wrapper to PwSh.Fw.Log's Wrte-ToLogFile().
 
    .DESCRIPTION
    All the Write-*() functions from this module use Write-ToLogFile(). This wrapper is here just in case the PwSh.Fw.Log module is not loaded/available.
 
    .PARAMETER Append
    Append message to the log file. Do not overwrite it.
    Append = $true is the default. If you want to overwrite or initiate the file, call
    Write-ToLogFile -message "Logfile initialized" -Append=$false
 
    .PARAMETER NoNewline
    Do not append a new line at the end of file.
 
    .PARAMETER NoHeader
    Do not print header informations : "date hostname scriptname". Usefull to append text to an existing line.
 
    .EXAMPLE
    Write-ToLogFile -message "a log entry" -append
 
#>

function Write-ToLogFile() {
    [CmdletBinding()]param(
        [switch]$Append,
        [switch]$NoNewLine,
        [switch]$NoHeader,
        [string]$message,
        [string]$logFile = $Global:LOG
    )
    # old method using ubounded arguments, but I failed to make it work
    # # Write-Host("`n >> " + $MyInvocation.MyCommand)
    # Write-Host($MyInvocation.PSBoundParameters | Convertto-Json)
    # Write-Host($MyInvocation.UnboundArguments | Convertto-Json)
    # $module = Get-Module PwSh.Fw.Log -ErrorAction SilentlyContinue
    # if ($null -ne $module) {
    # PwSh.Fw.Log\Write-ToLogFile $MyInvocation.PSBoundParameters
    # PwSh.Fw.Log\Write-ToLogFile ($MyInvocation.UnboundArguments).ToString()
    # }
    # # Write-Host("`n << " + $MyInvocation.MyCommand)

    # new method with bounded parameters
    $module = Get-Module PwSh.Fw.Log -ErrorAction SilentlyContinue
    if ($null -ne $module) {
        PwSh.Fw.Log\Write-ToLogFile -Append:$Append -NoNewLine:$NoNewLine -NoHeader:$NoHeader -Message "$Message" -logFile $logFile
    }

}

Set-Alias -Force -Name eindent        -Value Write-Indent
Set-Alias -Force -Name eoutdent        -Value Write-Outdent
Set-Alias -Force -Name etitle        -Value Write-Title
Set-Alias -Force -Name ebegin        -Value Write-Begin
Set-Alias -Force -Name eadd            -Value Write-Add
Set-Alias -Force -Name eend            -Value Write-End
Set-Alias -Force -Name fenter        -Value Write-EnterFunction
Set-Alias -Force -Name fleave        -Value Write-LeaveFunction
Set-Alias -Force -Name eenter        -Value Write-Enter
Set-Alias -Force -Name eleave        -Value Write-Leave
#Set-Alias -Force -Name einfo -Value Write-Information
Set-Alias -Force -Name einfo        -Value Write-Info
#Set-Alias -Force -Name everbose -Value Write-Verbose
Set-Alias -Force -Name everbose        -Value Write-MyVerbose
#Set-Alias -Force -Name edebug -Value Write-Debug
Set-Alias -Force -Name edebug        -Value Write-MyDebug
Set-Alias -Force -Name edevel        -Value Write-Devel
Set-Alias -Force -Name ewarn        -Value Write-MyWarning
Set-Alias -Force -Name eerror        -Value Write-MyError
Set-Alias -Force -Name efatal        -Value Write-Fatal