[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
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
    }
}

$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.Audio Stream Count','Measures.Audio Poor Stream Count','Measures.Audio Good Stream Count','Measures.Audio Unclassified Stream Count','Measures.Audio Poor Percentage','Measures.Audio Poor Due To Jitter Count','Measures.Audio Poor Due To PacketLoss Count','Measures.Audio Poor Due To Degradation Count','Measures.Audio Poor Due To RoundTrip Count','Measures.Audio Poor Due To ConcealedRatio Count'
$Dimentions ='AllStreams.Date','AllStreams.Hour','AllStreams.First IP Address','AllStreams.Second IP Address','AllStreams.Conference Id','AllStreams.Audio Poor Due To Jitter','AllStreams.Audio Poor Due To RoundTrip','AllStreams.Audio Poor Due To PacketLoss','AllStreams.Audio Poor Due To Degradation','AllStreams.Audio Poor Due To ConcealedRatio','AllStreams.Media Type','AllStreams.ClassifiedPoorCall','AllStreams.Is Teams','AllStreams.First UPN','AllStreams.Second UPN'

$AudioStmsOutput=Get-CQDData -Dimensions $Dimentions -StartDate $lstRptDat -EndDate $endDatStr  -Measures $measures -OutPutType DataTable -username $username -password $password -CQDVer V3  | Where-Object { $_.'Media Type' -eq 'Audio' -and [int]$_.Hour -gt $lstrptHr } | Where-Object {$_.'Is Teams' -eq '1' -or $_.'Is Teams' -eq $IsTeamsEnabled}

if($strtDatStr -ne $lstRptDat){
    $lstRptDat=$strtDatStr
    $lstrptHr=0
    $AudioStmsOutput+=Get-CQDData -Dimensions $Dimentions -StartDate $lstRptDat -EndDate $endDatStr  -Measures $measures -OutPutType DataTable -username $username -password $password -CQDVer V3  | Where-Object { $_.'Media Type' -eq 'Audio' -and [int]$_.Hour -ge $lstrptHr} | Where-Object {$_.'Is Teams' -eq '1' -or $_.'Is Teams' -eq $IsTeamsEnabled}
}
$AudioStmsOutput | 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){
    $AudioStreamCount = 0
    $AudioPoorStreamCount = 0
    $AudioGoodStreamCount = 0
    $AudioUnclassifiedStreamCount = 0
    $AudioPoorPercentage = 0
    $AudioOnePercentPacketLossCount = 0
    $AudioOnePercentPacketLossPercentage = 0
    $AudioPoorDueToJitterCount = 0
    $AudioPoorDueToPacketLossCount = 0
    $AudioPoorDueToDegradationCount = 0
    $AudioPoorDueToRoundTripCount = 0
    $AudioPoorDueToConcealedRatioCount = 0

    Write-host ' 1 *********************  AudioStreamCount measure***********************'
    $AudioStreamCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Stream Count')  -and $_.'Audio Stream Count' -ne 'NaN' }
    $AudioStreamCount = ($AudioStreamCountlist | Measure-Object "Audio Stream Count" -sum | select sum).sum
    if(-not $AudioStreamCount){  $AudioStreamCount=0 }  else { $AudioStreamCount=$AudioStreamCount.ToString("#.##") }
    $AudioStreamCountlist=$null

    if($AudioStreamCount){      
        Write-host '2********************* dd  AudioPoorStreamCount measure ***********************'
        $AudioPoorStreamCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Poor Stream Count')  -and $_.'Audio Poor Stream Count' -ne 'NaN' } 
        $AudioPoorStreamCount = ($AudioPoorStreamCountlist | Measure-Object "Audio Poor Stream Count" -sum | select sum).sum
        if(-not $AudioPoorStreamCount){  $AudioPoorStreamCount=0 } else { $AudioPoorStreamCount=$AudioPoorStreamCount.ToString("#.##") }

        if($AudioPoorStreamCount){
            $ddlist = $AudioPoorStreamCountlist | Where-Object { $_."Audio Poor Stream Count" -gt 0.0001 } | Sort-Object { $_."Audio Poor Stream Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddlist){ 
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAudioPoorStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference ID' ~!~ $in.'Audio Poor Stream Count'
            }
            $ddlist=$null
        }
        $AudioPoorStreamCountlist=$null

        Write-host '3********************* AudioGoodStreamCount measure ***********************'
        $AudioGoodStreamCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Good Stream Count')  -and $_.'Audio Good Stream Count' -ne 'NaN' } 
        $AudioGoodStreamCount = ($AudioGoodStreamCountlist | Measure-Object "Audio Good Stream Count" -sum | select sum).sum
        if(-not $AudioGoodStreamCount){  $AudioGoodStreamCount=0 } else { $AudioGoodStreamCount=$AudioGoodStreamCount.ToString("#.##") }
        $AudioGoodStreamCountlist=$null

        Write-host '4*********************  AudioUnclassifiedStreamCount measure ***********************'
        $AudioUnclassifiedStreamCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Unclassified Stream Count')  -and $_.'Audio Unclassified Stream Count' -ne 'NaN' } 
        $AudioUnclassifiedStreamCount = ($AudioUnclassifiedStreamCountlist | Measure-Object "Audio Unclassified Stream Count" -sum | select sum).sum
        if(-not $AudioUnclassifiedStreamCount){  $AudioUnclassifiedStreamCount=0 } else { $AudioUnclassifiedStreamCount=$AudioUnclassifiedStreamCount.ToString("#.##") }
        $AudioUnclassifiedStreamCountlist=$null

        Write-host '5*********************  AudioPoorPercentage measure ***********************'
        #$AudioPoorPercentagelist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Poor Percentage')  -and $_.'Audio Poor Percentage' -ne 'NaN' -and  $_."Audio Poor Percentage" -gt 0.0001 } 
        #$AudioPoorPercentage = ($AudioPoorPercentagelist | Measure-Object "Audio Poor Percentage" -Average | select Average).Average
        $AudioPoorPercentage = ($AudioPoorStreamCount/$AudioStreamCount)*100
        if(-not $AudioPoorPercentage){  $AudioPoorPercentage=0 }  else { $AudioPoorPercentage=$AudioPoorPercentage.ToString("#.##") }
        $AudioPoorPercentagelist=$null

        Write-host '8*********************dd  AudioPoorDueToJitterCount measure***********************'
        $AudioPoorDueToJitterCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Poor Due To Jitter Count') -and $_.'Audio Poor Due To Jitter Count' -ne 'NaN'  -and $_.'Audio Poor Due To Jitter' -ne 'TRUE' } 
        $AudioPoorDueToJitterCount = ($AudioPoorDueToJitterCountlist  | Measure-Object "Audio Poor Due To Jitter Count" -sum | select sum).sum
        if(-not $AudioPoorDueToJitterCount){  $AudioPoorDueToJitterCount=0 } else { $AudioPoorDueToJitterCount=$AudioPoorDueToJitterCount.ToString("#.##") }
        if($AudioPoorDueToJitterCount){
            $ddlist = $AudioPoorDueToJitterCountlist | Where-Object { $_."Audio Poor Due To Jitter Count" -gt 0.0001 } | Sort-Object { $_."Audio Poor Due To Jitter Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddlist){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAudioPoorDueToJitterCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference ID' ~!~ $in.'Audio Poor Due To Jitter Count'
            }
            $ddlist=$null
        }
        $AudioPoorDueToJitterCountlist=$null

        Write-host '9*********************dd AudioPoorDueToPacketLossCount measure ***********************'
        $AudioPoorDueToPacketLossCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Poor Due To PacketLoss Count')  -and $_.'Audio Poor Due To PacketLoss Count' -ne 'NaN'  -and $_.'Audio Poor Due To PacketLoss' -ne 'TRUE' } 
        $AudioPoorDueToPacketLossCount = ($AudioPoorDueToPacketLossCountlist  | Measure-Object "Audio Poor Due To PacketLoss Count" -sum | select sum).sum
        if(-not $AudioPoorDueToPacketLossCount){  $AudioPoorDueToPacketLossCount=0 } else { $AudioPoorDueToPacketLossCount=$AudioPoorDueToPacketLossCount.ToString("#.##") }
        if($AudioPoorDueToPacketLossCount){
            $ddlist = $AudioPoorDueToPacketLossCountlist | Where-Object { $_."Audio Poor Due To PacketLoss Count" -gt 0.0001 } | Sort-Object { $_."Audio Poor Due To PacketLoss Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddlist){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAudioPoorDueToPacketLossCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference ID' ~!~ $in.'Audio Poor Due To PacketLoss Count'
            }
            $ddlist=$null
        }
        $AudioPoorDueToPacketLossCountlist=$null

        Write-host '10********************* dd AudioPoorDueToDegradationCount measure ***********************'
        $AudioPoorDueToDegradationCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Poor Due To Degradation Count')  -and $_.'Audio Poor Due To Degradation Count' -ne 'NaN' -and $_.'Audio Poor Due To Degradation' -ne 'TRUE' } 
        $AudioPoorDueToDegradationCount = ($AudioPoorDueToDegradationCountlist  | Measure-Object "Audio Poor Due To Degradation Count" -sum | select sum).sum
        if(-not $AudioPoorDueToDegradationCount){  $AudioPoorDueToDegradationCount=0 } else { $AudioPoorDueToDegradationCount=$AudioPoorDueToDegradationCount.ToString("#.##") }
        if($AudioPoorDueToDegradationCount){
            $ddlist = $AudioPoorDueToDegradationCountlist | Where-Object { $_."Audio Poor Due To Degradation Count" -gt 0.0001 } | Sort-Object { $_."Audio Poor Due To Degradation Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddlist){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAudioPoorDueToDegradationCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference ID' ~!~ $in.'Audio Poor Due To Degradation Count'
            }
            $ddlist=$null
        }
        $AudioPoorDueToDegradationCountlist=$null

        Write-host '11********************* dd AudioPoorDueToRoundTripCount measure ***********************'
        $AudioPoorDueToRoundTripCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Poor Due To RoundTrip Count')  -and $_.'Audio Poor Due To RoundTrip Count' -ne 'NaN' -and $_.'Audio Poor Due To RoundTrip' -ne 'TRUE' } 
        $AudioPoorDueToRoundTripCount = ($AudioPoorDueToRoundTripCountlist  | Measure-Object "Audio Poor Due To RoundTrip Count" -sum | select sum).sum
        if(-not $AudioPoorDueToRoundTripCount){  $AudioPoorDueToRoundTripCount=0 } else { $AudioPoorDueToRoundTripCount=$AudioPoorDueToRoundTripCount.ToString("#.##") }
        if($AudioPoorDueToRoundTripCount){
            $ddlist = $AudioPoorDueToRoundTripCountlist | Where-Object { $_."Audio Poor Due To RoundTrip Count" -gt 0.0001 } | Sort-Object { $_."Audio Poor Due To RoundTrip Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddlist){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAudioPoorDueToRoundTripCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference ID' ~!~ $in.'Audio Poor Due To RoundTrip Count'
            }
            $ddlist=$null
        }
        $AudioPoorDueToRoundTripCountlist=$null

        Write-host '12********************* dd AudioPoorDueToConcealedRatioCount measure ***********************'
        $AudioPoorDueToConcealedRatioCountlist =$AudioStmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Audio Poor Due To ConcealedRatio Count')  -and $_.'Audio Poor Due To ConcealedRatio Count' -ne 'NaN' -and $_.'Audio Poor Due To ConcealedRatio' -ne 'TRUE' } 
        $AudioPoorDueToConcealedRatioCount = ($AudioPoorDueToConcealedRatioCountlist  | Measure-Object "Audio Poor Due To ConcealedRatio Count" -sum | select sum).sum
        if(-not $AudioPoorDueToConcealedRatioCount){  $AudioPoorDueToConcealedRatioCount=0 } else { $AudioPoorDueToConcealedRatioCount=$AudioPoorDueToConcealedRatioCount.ToString("#.##") }
        if($AudioPoorDueToConcealedRatioCount){
            $ddlist = $AudioPoorDueToConcealedRatioCountlist | Where-Object { $_."Audio Poor Due To ConcealedRatio Count" -gt 0.0001 } | Sort-Object { $_."Audio Poor Due To ConcealedRatio Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddlist){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAudioPoorDueToConcealedRatioCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference ID' ~!~ $in.'Audio Poor Due To ConcealedRatio Count'
            }
            $ddlist=$null
        }
        $AudioPoorDueToConcealedRatioCountlist=$null
    }
    Write-Host 'measures##' $AudioStreamCount ~ $AudioPoorStreamCount ~ $AudioGoodStreamCount ~ $AudioUnclassifiedStreamCount ~ $AudioPoorPercentage ~ $AudioPoorDueToJitterCount ~ $AudioPoorDueToPacketLossCount ~ $AudioPoorDueToDegradationCount ~ $AudioPoorDueToRoundTripCount ~ $AudioPoorDueToConcealedRatioCount
}