Function Get-LocalTime(){
	[CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=1)]
        [String]$dat, 
        [Parameter(Mandatory=$true, Position=2)]
        [String]$hr
    )
    Process
    {
        $ltimArr=@()
        $UTCTime=[DateTime]$dat
        $UTCTime=$UTCTime.AddHours([int]$hr)
        $strCurrentTimeZone = (Get-WmiObject win32_timezone).StandardName
        $TZ = [System.TimeZoneInfo]::FindSystemTimeZoneById($strCurrentTimeZone)
        $LocalTime = [System.TimeZoneInfo]::ConvertTimeFromUtc($UTCTime, $TZ)
        $ltimArr+='{0:yyyy-MM-dd}' -f $LocalTime
        $ltimArr+=(Get-Date $LocalTime).Hour
        Return $ltimArr
    }
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egurkhaPath=(Get-Item Env:EGURKHA_INSTALL_DIR).value.ToString()
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
$cqdModule=$scriptPath+"\MTMCallQlityReport.psm1"
Import-Module $egEncryPath,$egDatnKy,$cqdModule
clear

$TestInputs=$args
$userName=$TestInputs[0]
$password=Eg-O365Dcr -EncStr $TestInputs[1]
$mperiodAndIsTeam=$TestInputs[2].ToString().Split('#')
$mPeriodInMin=[int]$mperiodAndIsTeam[0].Trim()
$IsTeamsEnabled=$mperiodAndIsTeam[1].Trim()
$rptDateHr=$mperiodAndIsTeam[2].Trim()
$prxyCrds=$TestInputs[3].ToString().Split('#')
$proxyUsr=$prxyCrds[0]
$proxyPass=Eg-O365Dcr -EncStr $prxyCrds[1]
$proxyserverip=($TestInputs[4]).ToString().trim()

$dat1=(Get-Date).AddMinutes(-($mPeriodInMin))
$dat2=$dat1.ToUniversalTime()
$hr=$dat2.Hour
$strtDatStr='{0:yyyy-MM-dd}' -f $dat2
$endDatStr='{0:yyyy-MM-dd}' -f $dat2.AddDays(1)
if($rptDateHr -ne 'none'){
    $arr=$rptDateHr.Split('~')
    $lstRptDat=$arr[0]
    $chkrptDat=$lstRptDat
    $lstrptHr=$arr[1]
    $chkrptHr=$lstrptHr
    $chkPnt=$arr[2] 
}else{
    $lstRptDat=$strtDatStr
    $lstrptHr=$hr
}

$credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $password -asplaintext -force)
if(!$proxyserverip.ToString().ToLower().Contains('none')){
    $proxyserver='http://'+$proxyserverip
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUsr.ToString().ToLower() -ne 'none' -and $proxyPass.ToString().ToLower() -ne 'none'){
        $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
        [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred   #[System.Net.CredentialCache]::DefaultNetworkCredentials
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
 }
#$measures='Measures.Avg Audio Degradation','Measures.Avg Jitter','Measures.Avg Jitter Max','Measures.Avg Packet Loss Rate','Measures.Avg Packet Loss Rate Max','Measures.Avg Send Listen MOS','Measures.Avg Overall Avg Network MOS','Measures.Avg Ratio Concealed Samples','Measures.Avg Conceal Ratio Max','Measures.Avg Ratio Stretched Samples','Measures.Avg Round Trip','Measures.Avg Round Trip Max','Measures.Avg Network Jitter','Measures.Avg Network Jitter Max','Measures.Avg Network Jitter Min'
$measures='Measures.Avg Audio Degradation','Measures.Avg Jitter','Measures.Avg Jitter Max','Measures.Avg Packet Loss Rate','Measures.Avg Packet Loss Rate Max','Measures.Avg Send Listen MOS','Measures.Avg Overall Avg Network MOS','Measures.Avg Ratio Concealed Samples','Measures.Avg Ratio Stretched Samples','Measures.Avg Round Trip','Measures.Avg Round Trip Max'
$Dimentions ='AllStreams.First IP Address','AllStreams.Second IP Address','AllStreams.Date','AllStreams.Hour','AllStreams.Conference Id','AllStreams.Is Teams','AllStreams.First UPN','AllStreams.Second UPN'

$NtwkQltySmryOutput=Get-CQDData -Dimensions $Dimentions -StartDate $lstRptDat -EndDate $endDatStr  -Measures $measures -OutPutType DataTable -username $username -password $password -CQDVer V3 | Where-Object {[int]$_.Hour -gt $lstrptHr} | Where-Object {$_.'Is Teams' -eq '1' -or $_.'Is Teams' -eq $IsTeamsEnabled}
if($strtDatStr -ne $lstRptDat){
    $lstRptDat=$strtDatStr
    $lstrptHr=0
    $NtwkQltySmryOutput+=Get-CQDData -Dimensions $Dimentions -StartDate $lstRptDat -EndDate $endDatStr  -Measures $measures -OutPutType DataTable -username $username -password $password -CQDVer V3 | Where-Object {[int]$_.Hour -ge $lstrptHr} | Where-Object {$_.'Is Teams' -eq '1' -or $_.'Is Teams' -eq $IsTeamsEnabled}
}
$NtwkQltySmryOutput | select * | ForEach-Object {if($_.Date -eq $lstRptDat -and $_.Hour -gt $lstrptHr){$lstrptHr=$_.Hour};}

$isWrite=$true
if($lstRptDat -eq $chkrptDat -and $lstrptHr -eq $chkrptHr){
    $chkPnt=[int]$chkPnt+1
    if([int]$chkPnt -gt 1){
        $isWrite=$false
    }
}else{
    $chkPnt=1
}
$rptDatHrstr='LastReporting Date and Hour#'+$lstRptDat+'~'+$lstrptHr+'~'+$chkPnt
Write-Host $rptDatHrstr

if($isWrite){
    $AvgAudioDegradation = 0
    $AvgJitter = 0
    $AvgJitterMax = 0
    $AvgPacketLossRate = 0
    $AvgPacketLossRateMax = 0
    $AvgSendListenMOS = 0
    $AvgOverallAvgNetworkMOS = 0
    $AvgRatioConcealedSamples = 0
    $AvgRatioStretchedSamples = 0
    $AvgRoundTrip = 0
    $AvgRoundTripMax = 0

    if($NtwkQltySmryOutput){
        Write-host '*********************  AvgAudioDegradation measure***********************'
        $AvgAudioDegradationlist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Audio Degradation')  -and $_.'Avg Audio Degradation' -ne 'NaN' -and $_.'Avg Audio Degradation' -gt 0.0001}
        $AvgAudioDegradation = ($AvgAudioDegradationlist | Measure-Object "Avg Audio Degradation" -Average | select Average).Average
        if(-not $AvgAudioDegradation){  $AvgAudioDegradation=0 }  else { $AvgAudioDegradation=$AvgAudioDegradation.ToString("#.##") }
        $AvgAudioDegradationlist=$null

        Write-host '*********************  AvgJitter measure ***********************'
        $AvgJitterlist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Jitter')  -and $_.'Avg Jitter' -ne 'NaN' -and $_.'Avg Jitter' -gt 0.0001} 
        $AvgJitter = ($AvgJitterlist | Measure-Object "Avg Jitter" -Average | select Average).Average
        if(-not $AvgJitter){  $AvgJitter=0 } else { $AvgJitter=$AvgJitter.ToString("#.##") }
        if($AvgJitter){
            $ddlist = $AvgJitterlist | Where-Object { $_."Avg Jitter" -gt 0.0001 } | Sort-Object { $_."Avg Jitter" -as [int] } -Descending | select -First 10
            foreach($in in $ddlist){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAvgJitter#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Avg Jitter'
            }
            $ddlist=$null
        }
        $AvgJitterlist=$null

        Write-host '********************* AvgJitterMax measure ***********************'
        $AvgJitterMaxlist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Jitter Max')  -and $_.'Avg Jitter Max' -ne 'NaN' -and $_.'Avg Jitter Max' -gt 0.0001} 
        $AvgJitterMax = ($AvgJitterMaxlist | Measure-Object "Avg Jitter Max" -Average | select Average).Average
        if(-not $AvgJitterMax){  $AvgJitterMax=0 } else { $AvgJitterMax=$AvgJitterMax.ToString("#.##") }
        $AvgJitterMaxlist=$null

        Write-host '*********************  AvgPacketLossRate measure ***********************'
        $AvgPacketLossRatelist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Packet Loss Rate')  -and $_.'Avg Packet Loss Rate' -ne 'NaN' -and $_.'Avg Packet Loss Rate' -gt 0.0001 } 
        $AvgPacketLossRate = ($AvgPacketLossRatelist | Measure-Object "Avg Packet Loss Rate" -Average | select Average).Average
        if(-not $AvgPacketLossRate){  $AvgPacketLossRate=0 } else { $AvgPacketLossRate=($AvgPacketLossRate*100).ToString("#.##") }
        $AvgPacketLossRatelist=$null

        Write-host '*********************  AvgPacketLossRateMax measure***********************'
        $AvgPacketLossRateMaxlist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Packet Loss Rate Max')  -and $_.'Avg Packet Loss Rate Max' -ne 'NaN' -and $_.'Avg Packet Loss Rate Max' -gt 0.0001 } 
        $AvgPacketLossRateMax = ($AvgPacketLossRateMaxlist | Measure-Object "Avg Packet Loss Rate Max" -Average | select Average).Average
        if(-not $AvgPacketLossRateMax){  $AvgPacketLossRateMax=0 }  else { $AvgPacketLossRateMax=($AvgPacketLossRateMax*100).ToString("#.##") }
        $AvgPacketLossRateMaxlist=$null

        Write-host '*********************  AvgSendListenMOS measure***********************'
        $AvgSendListenMOSlist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Send Listen MOS')  -and $_.'Avg Send Listen MOS' -ne 'NaN' -and $_.'Avg Send Listen MOS' -gt 0.0001 } 
        $AvgSendListenMOS = ($AvgSendListenMOSlist | Measure-Object "Avg Send Listen MOS" -Average | select Average).Average
        if(-not $AvgSendListenMOS){  $AvgSendListenMOS=0 } else { $AvgSendListenMOS=$AvgSendListenMOS.ToString("#.##") }
        $AvgSendListenMOSlist=$null

        Write-host '*********************  AvgOverallAvgNetworkMOS measure***********************'
        $AvgOverallAvgNetworkMOSlist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Overall Avg Network MOS')  -and $_.'Avg Overall Avg Network MOS' -ne 'NaN' -and $_.'Avg Overall Avg Network MOS' -gt 0.0001 } 
        $AvgOverallAvgNetworkMOS = ($AvgOverallAvgNetworkMOSlist | Measure-Object "Avg Overall Avg Network MOS" -Average | select Average).Average
        if(-not $AvgOverallAvgNetworkMOS){  $AvgOverallAvgNetworkMOS=0 } else { $AvgOverallAvgNetworkMOS=$AvgOverallAvgNetworkMOS.ToString("#.##") }
        $AvgOverallAvgNetworkMOSlist=$null

        Write-host '*********************  AvgRatioConcealedSamples measure***********************'
        $AvgRatioConcealedSampleslist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Ratio Concealed Samples')  -and $_.'Avg Ratio Concealed Samples' -ne 'NaN' -and $_.'Avg Ratio Concealed Samples' -gt 0.0001} 
        $AvgRatioConcealedSamples = ($AvgRatioConcealedSampleslist  | Measure-Object "Avg Ratio Concealed Samples" -Average | select Average).Average
        if(-not $AvgRatioConcealedSamples){  $AvgRatioConcealedSamples=0 } else { $AvgRatioConcealedSamples=($AvgRatioConcealedSamples*100).ToString("#.##") }
        $AvgRatioConcealedSampleslist=$null

        Write-host '********************* AvgRatioStretchedSamples measure ***********************'
        $AvgRatioStretchedSampleslist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Ratio Stretched Samples')  -and $_.'Avg Ratio Stretched Samples' -ne 'NaN' -and $_.'Avg Ratio Stretched Samples' -gt 0.0001 } 
        $AvgRatioStretchedSamples = ($AvgRatioStretchedSampleslist  | Measure-Object "Avg Ratio Stretched Samples" -Average | select Average).Average
        if(-not $AvgRatioStretchedSamples){  $AvgRatioStretchedSamples=0 } else { $AvgRatioStretchedSamples=($AvgRatioStretchedSamples*100).ToString("#.##") }
        $AvgRatioStretchedSampleslist=$null

        Write-host '********************* AvgRoundTrip measure ***********************'
        $AvgRoundTriplist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Round Trip')  -and $_.'Avg Round Trip' -ne 'NaN' -and $_.'Avg Round Trip' -gt 0.0001 } 
        $AvgRoundTrip = ($AvgRoundTriplist  | Measure-Object "Avg Round Trip" -Average | select Average).Average
        if(-not $AvgRoundTrip){  $AvgRoundTrip=0 } else { $AvgRoundTrip=$AvgRoundTrip.ToString("#.##") }
        $AvgRoundTriplist=$null

        Write-host '********************* AvgRoundTripMax measure ***********************'
        $AvgRoundTripMaxlist =$NtwkQltySmryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Round Trip Max')  -and $_.'Avg Round Trip Max' -ne 'NaN' -and $_.'Avg Round Trip Max' -gt 0.0001} 
        $AvgRoundTripMax = ($AvgRoundTripMaxlist  | Measure-Object "Avg Round Trip Max" -Average | select Average).Average
        if(-not $AvgRoundTripMax){  $AvgRoundTripMax=0 } else { $AvgRoundTripMax=$AvgRoundTripMax.ToString("#.##") }
        $AvgRoundTripMaxlist=$null

        Write-Host 'measures##' $AvgAudioDegradation ~ $AvgJitter ~ $AvgJitterMax ~ $AvgPacketLossRate ~ $AvgPacketLossRateMax ~ $AvgSendListenMOS ~ $AvgOverallAvgNetworkMOS ~ $AvgRatioConcealedSamples ~ $AvgRatioStretchedSamples ~ $AvgRoundTrip ~ $AvgRoundTripMax
    }
}