﻿function Get-ProcessorArchitecture {
    return $env:AssessmentExecutionArchitecture
}

# This function will write what is piped to it as a string to the default output
# (usually the host/console) and also to the log file if running under axe.
#
function Log-Info() {
    PROCESS {
        if ( $_ ) {
            "$_" | Out-Default
            if ( $Global:axeLogger ) {
                $Global:axeLogger.LogMessage( "$_" )
            }
        }
    }
}

function Log-Error([int32]$ErrorCode=1) {
    PROCESS {
        if ( $_ ) {
            "$_" | Write-Error
            if ( $Global:axeLogger ) {
                $Global:axeLogger.LogErrorCode( $ErrorCode, "$_" )
            }
        }
   }
}

function InitializeAxeLogger {
    Param( 
        [parameter(Mandatory=$true)][string]$AxeCoreNet
    )

    $boolRunningUnderAxe = $false
    if ( Test-Path $AxeCoreNet ) {
        $axeAssembly = [Reflection.Assembly]::LoadFrom( $AxeCoreNet )
        if ( $axeAssembly ) {
            $Global:axeSupport = [Microsoft.Assessments.Runtime.Support]::Initialize()
            if ( $Global:axeSupport ) {
                $boolRunningUnderAxe = $Global:axeSupport.EngineRunning
                $Global:axeLogger = $Global:axeSupport.CreateLogger()
            }
        }
    }
    
    # Make sure we've set up the environment properly
    #
    if ( -not $boolRunningUnderAxe ) {
        "This script only works when run from the Axe framework." | Log-Error
        Exit 1
    }
    
    $boolRunningUnderAxe
}

function LogToXmlErrorFile {
    Param(
        [parameter(Mandatory=$true)][String]$XmlErrorFile,
        [parameter(Mandatory=$true)]$ErrorCode,
        [parameter(Mandatory=$true)][String]$ErrorMessage
    )
    
    try
    {
        $XmlWriter = $Global:axeSupport.CreateResultSnippet()
        $XmlWriter.AddError([Convert]::ToUInt32("{0:X0}" -f $ErrorCode), $ErrorMessage)
        $XmlWriter.Save($XmlErrorFile)
    }
    catch [Exception]
    {
        # Log the exeption to AXE log
        "Error occured while writing the Errors XML file" | Log-Error
        $_.Exception | Format-List -Force | Log-Error
    }
}

Export-ModuleMember Get-ProcessorArchitecture
Export-ModuleMember Log-Error
Export-ModuleMember Log-Info
Export-ModuleMember InitializeAxeLogger
Export-ModuleMember LogToXmlErrorFile
