# example usage:
#     .\ShowGuiMessage.ps1 -VMName $vmName -messageText "Your current session ends in 5 minutes.`nIf you want to continue playing, go to the AOFG Dashboard and extend your session.`nOtherwise you should exit the game soon to save your progress." -messageColor "cRed" -AdminPassword "Password123" -messageDisplayTimeMs 10000

param(
    [Parameter(Mandatory = $true)]
    [string]$vmName,
    [Parameter(Mandatory = $true)]
    [string]$messageText,
    [Parameter(Mandatory = $false)]
    [ValidateSet("cBlack", "cSilver", "cGray", "cWhite", "cMaroon", "cRed", "cPurple", "cFuchsia", "cGreen", "cLime", "cOlive", "cYellow", "cNavy", "cBlue", "cTeal", "cAqua")]
    [string]$messageColor = "cYellow",
    [Parameter(Mandatory = $false)]
    [uint32]$messageDisplayTimeSeconds = 10,
    [Parameter(Mandatory = $true)]
    [string]$vmPassword
)

Set-Location $PSScriptRoot
.("..\AOFLibrary\AOFLibrary.ps1")

<#
Color   Hex Code
Black	000000
Silver	C0C0C0
Gray	808080
White	FFFFFF
Maroon	800000
Red	    FF0000
Purple	800080
Fuchsia	FF00FF
Green	008000
Lime	00FF00
Olive	808000
Yellow	FFFF00
Navy	000080
Blue	0000FF
Teal	008080
Aqua	00FFFF
#>

$ScriptName = "ShowGuiMessage"
$LogFile = BeginScriptLogging -ScriptName $ScriptName

$password = ConvertTo-SecureString $vmPassword -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("Administrator", $password)

$messageDisplayTimeMs = $messageDisplayTimeSeconds * 1000

try {
    Invoke-Command -VMName $vmName -Credential $cred -ArgumentList $messageText, $messageColor, $messageDisplayTimeMs -ScriptBlock {
        param($messageText, $messageColor, $messageDisplayTimeMs)

        if(-not (Test-Path ($env:ProgramData + "\Parsec\user.bin")))
        {
            throw "No Parsec account is logged in"
        }

        $pipeName = "aofg_message_overlay"
        $pipeClient = New-Object System.IO.Pipes.NamedPipeClientStream '.', $pipeName, 'Out'
        $pipeClient.Connect()
        $writer = New-Object System.IO.StreamWriter $pipeClient
        $writer.WriteLine($messageColor)
        $writer.WriteLine($messageDisplayTimeMs)
        $writer.WriteLine($messageText)
        $writer.Close()
        $pipeClient.Close()
    } -ErrorAction Stop
    Write-Log -Message "Script executed successfully" -Level INFO -Log $LogFile
}
catch {
    HandleScriptExecutionError -Message "Unable to display the message: $($PSItem.Exception.message)" -Log $LogFile
}

Write-ScriptSuccess -Log $LogFile
