# this script is executed at startup AND those scripts are executed in alphabetical order AND .\ParsecLogin.ps1 must execute BEFORE this script

$ahkScript = "C:\AOFG\ShowOverlayGuiMessage.ahk"
$ahkExecutable = "C:\Program Files\AutoHotkey\v2\AutoHotkey64.exe"

$dateFormat = "dd-MM-yyyy HH \h mm \min ss \s"
function Get-FormattedDate() {
    return (Get-Date -Format $dateFormat)
}

function Escape-Argument {
    param([string]$arg)

    # Escape internal quotes: replace " with `"
    $escaped = $arg -replace '"', '\"'

    # Surround the whole thing with quotes
    return '"' + $escaped + '"'
}

while($true)
{
    $credentialsPipe = "aofg_message_overlay"
    # Create a named pipe server
    $credentialsPipeServer = New-Object System.IO.Pipes.NamedPipeServerStream $credentialsPipe, 'In'
    try {
        # Wait for a connection from the client
        $credentialsPipeServer.WaitForConnection()
        # Read the data sent by the client
        $messageReader = New-Object System.IO.StreamReader $credentialsPipeServer
        $messageColor = $messageReader.ReadLine()
        $messageDisplayTimeMs = $messageReader.ReadLine()
        $messageText = $messageReader.ReadLine()

        # Process the message
        $messageColor = Escape-Argument $messageColor
        $messageDisplayTimeMs = Escape-Argument $messageDisplayTimeMs
        $messageText = Escape-Argument $messageText

        $arguments = "$ahkScript $messageColor $messageDisplayTimeMs $messageText"
        $processInfo = New-Object System.Diagnostics.ProcessStartInfo
        $processInfo.FileName = $ahkExecutable
        $processInfo.Arguments = $arguments
        $processInfo.RedirectStandardOutput = $true
        $processInfo.UseShellExecute = $false
        $processInfo.CreateNoWindow = $true
    
        $process = New-Object System.Diagnostics.Process
        $process.StartInfo = $processInfo
        $process.Start() | Out-Null

        $process.WaitForExit()
    }
    finally {
        $messageReader.Close()
        $messageReader.Dispose()
        $credentialsPipeServer.Close()
        $credentialsPipeServer.Dispose()
    }
}
