#
# UdpCheck.ps1
#

. ".\Common.ps1"

# Set up variables
$qloiws04LniataVdu 		= "ba0252"
$sharesIpUdp 			= "204.26.250.37"
$sharesUdpPorts     	= 3020, 3024

function CheckUdp {
	param(
		[parameter(Mandatory=$true)]
		[int]
		$port)
	try
	{
		$ta = $qloiws04LniataVdu.substring(4,2);
		$taInt = [int]"0x$($ta)"
		$clientPort = 3000 + $taInt
		$client = new-Object system.Net.Sockets.Udpclient $clientPort
	}
	catch
	{
		Write-Warning "$($Error[0])"
		$client = new-Object system.Net.Sockets.Udpclient
	}
	$client.client.ReceiveTimeout = 5000
	$client.Connect($sharesIpUdp, $port)
	$requestData = "$($qloiws04LniataVdu)4e"
	$bytes = Build-SharesMessage($requestData)
	#$clientEndpoint = [IPEndPoint]($client.Client.LocalEndPoint)
	$clientEndpoint = $client.Client.LocalEndPoint
	[void]$client.Send($bytes, $bytes.length)
	$endpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any, 0)
	$udpConnectivity = $false
	$responseData
	try
	{
		$bytes = $client.Receive( [ref]$endpoint )
		$udpConnectivity = $true
		$responseData = Convert-ByteArrayToHex $bytes
	}
	catch
	{
		$udpConnectivity = $false
		# Write-Warning "UDP test result. FAIL. Error: $($Error[0])"
	}
	finally
	{
		$client.Close();
	}
	New-Object PsObject -Property @{
		SHARES_Host = $sharesIpUdp
		SHARES_Port = $port
		HasConnectivity = $udpConnectivity
		ClientEndpoint = "$($clientEndpoint.Address.IPAddressToString):$($clientEndpoint.Port)"
	}
}

Write-Output "`r`n`r`nUDP CONNECTIVITY TEST:"
foreach ($port in $sharesUdpPorts)
{
	$result = CheckUdp -port $port
	$result -replace "[`r`n]+$", "" >$null
	Write-Output $result
}
# $udpTestOut = "UDP Connectivity "
# if ($udpConnectivity)
# {
# 	$udpTestOut = "$($udpTestOut)True"
# }
# else
# {
# 	$udpTestOut = "$($udpTestOut)False"
# }
# Write-Output $udpTestOut