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.Video Stream Count','Measures.Video Poor Due To VideoPostFecplr Count','Measures.Video Poor Due To VideoLocalFrameLossPercentageAvg Count','Measures.Video Poor Due To VideoFrameRateAvg Count','Measures.Video Poor Stream Count','Measures.Video Good Stream Count','Measures.Video Unclassified Stream Count','Measures.Video Poor Percentage','Measures.Avg Video Post FECPLR','Measures.Avg Video Local Frame Loss Percentage','Measures.Avg Video Recv Frame Rate Average','Measures.Avg Video Low Frame Rate Call Percent','Measures.Avg Video Packet Loss Rate','Measures.Avg Video Frame Rate','Measures.Avg Video Dynamic Capability Percent'
$Dimentions ='AllStreams.Date','AllStreams.Hour','AllStreams.First IP Address','AllStreams.Second IP Address','AllStreams.Conference Id','AllStreams.Is Teams','AllStreams.Media Type','AllStreams.ClassifiedPoorCall','AllStreams.First UPN','AllStreams.Second UPN'

$VideoSumryOutput=Get-CQDData -Dimensions $Dimentions -StartDate $lstRptDat -EndDate $endDatStr  -Measures $measures -OutPutType DataTable -username $username -password $password -CQDVer V3 | Where-Object { $_.'Media Type' -eq 'Video' -and [int]$_.Hour -gt $lstrptHr} | Where-Object {$_.'Is Teams' -eq '1' -or $_.'Is Teams' -eq $IsTeamsEnabled}
if($strtDatStr -ne $lstRptDat){
    $lstRptDat=$strtDatStr
    $lstrptHr=0
    $VideoSumryOutput+=Get-CQDData -Dimensions $Dimentions -StartDate $lstRptDat -EndDate $endDatStr  -Measures $measures -OutPutType DataTable -username $username -password $password -CQDVer V3 | Where-Object { $_.'Media Type' -eq 'Video' -and [int]$_.Hour -ge $lstrptHr} | Where-Object {$_.'Is Teams' -eq '1' -or $_.'Is Teams' -eq $IsTeamsEnabled}
}
$VideoSumryOutput | 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){
    $VideoStreamCount= 0 
    $VideoPoorDueToVideoPostFecplrCount= 0 
    $VideoPoorDueToVideoLocalFrameLossPercentageAvgCount= 0 
    $VideoPoorDueToVideoFrameRateAvgCount= 0 
    $VideoPoorStreamCount= 0 
    $VideoGoodStreamCount= 0 
    $VideoUnclassifiedStreamCount= 0 
    $VideoPoorPercentage= 0 
    $AvgVideoPostFECPLR= 0 
    $AvgVideoLocalFrameLossPercentage= 0 
    $AvgVideoRecvFrameRateAverage= 0 
    $AvgVideoLowFrameRateCallPercent= 0 
    $AvgVideoPacketLossRate= 0 
    $AvgVideoDynamicCapabilityPercent= 0

    if($VideoSumryOutput){
        $VideoStreamCountlist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Video Stream Count')  -and $_.'Video Stream Count' -ne 'NaN' } 
        $VideoStreamCount = ($VideoStreamCountlist| Measure-Object "Video Stream Count" -Sum | select Sum).Sum
        if(-not $VideoStreamCount){  $VideoStreamCount=0 }
        $VideoStreamCountlist=$null

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

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

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

        Write-host '********************* dd VideoPoorStreamCount measure***********************'
        $VideoPoorStreamCountlist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Video Poor Stream Count')  -and $_.'Video Poor Stream Count' -ne 'NaN' } 
        $VideoPoorStreamCount = ($VideoPoorStreamCountlist | Measure-Object "Video Poor Stream Count" -Sum | select Sum).Sum
        if(-not $VideoPoorStreamCount){  $VideoPoorStreamCount=0 }  else { $VideoPoorStreamCount=$VideoPoorStreamCount.ToString("#.##") }
        if($VideoPoorStreamCount){
            $ddlist = $VideoPoorStreamCountlist | Where-Object { $_."Video Poor Stream Count" -gt 0.0001 } | Sort-Object { $_."Video Poor Stream Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddlist){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddVideoPoorStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'Video Poor Stream Count' ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference Id'
            }
            $ddlist=$null
        }
        $VideoPoorStreamCountlist=$null

        $VideoGoodStreamCountlist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Video Good Stream Count')  -and $_.'Video Good Stream Count' -ne 'NaN' } 
        $VideoGoodStreamCount = ($VideoGoodStreamCountlist | Measure-Object "Video Good Stream Count" -Sum | select Sum).Sum
        if(-not $VideoGoodStreamCount){  $VideoGoodStreamCount=0 } else { $VideoGoodStreamCount=$VideoGoodStreamCount.ToString("#.##") }

        $VideoUnclassifiedStreamCountlist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Video Unclassified Stream Count')  -and $_.'Video Unclassified Stream Count' -ne 'NaN' } 
        $VideoUnclassifiedStreamCount = ($VideoUnclassifiedStreamCountlist | Measure-Object "Video Unclassified Stream Count" -Sum | select Sum).Sum
        if(-not $VideoUnclassifiedStreamCount){  $VideoUnclassifiedStreamCount=0 } else { $VideoUnclassifiedStreamCount=$VideoUnclassifiedStreamCount.ToString("#.##") }
        $VideoUnclassifiedStreamCountlist=$null

        Write-host '********************* VideoPoorPercentage measure***********************'
        #$VideoPoorPercentagelist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Video Poor Percentage')  -and $_.'Video Poor Percentage' -ne 'NaN' -and $_.'Video Poor Percentage' -gt 0.0001 } 
        #$VideoPoorPercentage = ($VideoPoorPercentagelist  | Measure-Object "Video Poor Percentage" -Average | select Average).Average
        $VideoPoorPercentage = ($VideoPoorStreamCount/$VideoStreamCount)/100
        if(-not $VideoPoorPercentage){  $VideoPoorPercentage=0 } else { $VideoPoorPercentage=$VideoPoorPercentage.ToString("#.##") }
        $VideoPoorPercentagelist=$null

        $AvgVideoPostFECPLRlist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Video Post FECPLR')  -and $_.'Avg Video Post FECPLR' -ne 'NaN' -and $_.'Avg Video Post FECPLR' -gt 0.0001 } 
        $AvgVideoPostFECPLR = ($AvgVideoPostFECPLRlist  | Measure-Object "Avg Video Post FECPLR" -Average | select Average).Average
        if(-not $AvgVideoPostFECPLR){  $AvgVideoPostFECPLR=0 } else { $AvgVideoPostFECPLR=($AvgVideoPostFECPLR*100).ToString("#.##") }
        $AvgVideoPostFECPLRlist=$null

        $AvgVideoLocalFrameLossPercentagelist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Video Local Frame Loss Percentage')  -and $_.'Avg Video Local Frame Loss Percentage' -ne 'NaN' -and $_.'Avg Video Local Frame Loss Percentage' -gt 0.0001 } 
        $AvgVideoLocalFrameLossPercentage = ($AvgVideoLocalFrameLossPercentagelist  | Measure-Object "Avg Video Local Frame Loss Percentage" -Average | select Average).Average
        if(-not $AvgVideoLocalFrameLossPercentage){  $AvgVideoLocalFrameLossPercentage=0 }  else { $AvgVideoLocalFrameLossPercentage=$AvgVideoLocalFrameLossPercentage.ToString("#.##") }
        $AvgVideoLocalFrameLossPercentagelist=$null

        $AvgVideoRecvFrameRateAveragelist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Video Recv Frame Rate Average')  -and $_.'Avg Video Recv Frame Rate Average' -ne 'NaN' -and $_.'Avg Video Recv Frame Rate Average' -gt 0.0001 } 
        $AvgVideoRecvFrameRateAverage = ($AvgVideoRecvFrameRateAveragelist  | Measure-Object "Avg Video Recv Frame Rate Average" -Average | select Average).Average
        if(-not $AvgVideoRecvFrameRateAverage){  $AvgVideoRecvFrameRateAverage=0 }  else { $AvgVideoRecvFrameRateAverage=$AvgVideoRecvFrameRateAverage.ToString("#.##") }
        $AvgVideoRecvFrameRateAveragelist=$null

        $AvgVideoLowFrameRateCallPercentlist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Video Low Frame Rate Call Percent')  -and $_.'Avg Video Low Frame Rate Call Percent' -ne 'NaN' -and $_.'Avg Video Low Frame Rate Call Percent' -gt 0.0001 } 
        $AvgVideoLowFrameRateCallPercent = ($AvgVideoLowFrameRateCallPercentlist  | Measure-Object "Avg Video Low Frame Rate Call Percent" -Average | select Average).Average
        if(-not $AvgVideoLowFrameRateCallPercent){  $AvgVideoLowFrameRateCallPercent=0 } else { $AvgVideoLowFrameRateCallPercent=$AvgVideoLowFrameRateCallPercent.ToString("#.##") }
        $AvgVideoLowFrameRateCallPercentlist=$null

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

        $AvgVideoDynamicCapabilityPercentlist =$VideoSumryOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg Video Dynamic Capability Percent')  -and $_.'Avg Video Dynamic Capability Percent' -ne 'NaN' -and $_.'Avg Video Dynamic Capability Percent' -gt 0.0001 } 
        $AvgVideoDynamicCapabilityPercent = ($AvgVideoDynamicCapabilityPercentlist  | Measure-Object "Avg Video Dynamic Capability Percent" -Average | select Average).Average
        if(-not $AvgVideoDynamicCapabilityPercent){  $AvgVideoDynamicCapabilityPercent=0 } else { $AvgVideoDynamicCapabilityPercent=$AvgVideoDynamicCapabilityPercent.ToString("#.##") }
        $AvgVideoDynamicCapabilityPercentlist=$null

        Write-Host 'measures##' $VideoStreamCount ~ $VideoPoorDueToVideoPostFecplrCount ~ $VideoPoorDueToVideoLocalFrameLossPercentageAvgCount ~ $VideoPoorDueToVideoFrameRateAvgCount ~ $VideoPoorStreamCount ~ $VideoGoodStreamCount ~ $VideoUnclassifiedStreamCount ~ $VideoPoorPercentage ~ $AvgVideoPostFECPLR ~ $AvgVideoLocalFrameLossPercentage ~ $AvgVideoRecvFrameRateAverage ~ $AvgVideoLowFrameRateCallPercent ~ $AvgVideoPacketLossRate ~ $AvgVideoDynamicCapabilityPercent
    }
}