[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.AppSharing Stream Count','Measures.AppSharing Poor Due To SpoiledTilePercentTotal Count','Measures.AppSharing Poor Due To RelativeOneWayAverage Count','Measures.AppSharing Poor Due To RDPTileProcessingLatencyAverage Count','Measures.AppSharing Poor Stream Count','Measures.AppSharing Good Stream Count','Measures.AppSharing Unclassified Stream Count','Measures.AppSharing Poor Percentage','Measures.Avg AppSharing Spoiled Tile Percent Total','Measures.Avg AppSharing Relative OneWay','Measures.Avg AppSharing RDP Tile Processing Latency','Measures.Avg Relative OneWay','Measures.Avg Relative OneWay Max'
$Dimentions ='AllStreams.Date','AllStreams.Hour','AllStreams.First IP Address','AllStreams.Second IP Address','AllStreams.Conference Id','AllStreams.AppSharing Poor Due To SpoiledTilePercentTotal','AllStreams.AppSharing Poor Due To RelativeOneWayAverage','AllStreams.AppSharing Poor Due To RDPTileProcessingLatencyAverage','AllStreams.ClassifiedPoorCall','AllStreams.Is Teams','AllStreams.Media Type','AllStreams.First UPN','AllStreams.Second UPN'

$AppShrngStrmsOutput=Get-CQDData -Dimensions $Dimentions -StartDate $lstRptDat -EndDate $endDatStr  -Measures $measures -OutPutType DataTable -username $username -password $password -CQDVer V3  | Where-Object { $_.'Media Type' -eq 'AppSharing' -and [int]$_.Hour -gt $lstrptHr} | Where-Object {$_.'Is Teams' -eq '1' -or $_.'Is Teams' -eq $IsTeamsEnabled}
if($strtDatStr -ne $lstRptDat){
    $lstRptDat=$strtDatStr
    $lstrptHr=0
    $AppShrngStrmsOutput+=Get-CQDData -Dimensions $Dimentions -StartDate $lstRptDat -EndDate $endDatStr  -Measures $measures -OutPutType DataTable -username $username -password $password -CQDVer V3  | Where-Object { $_.'Media Type' -eq 'AppSharing' -and [int]$_.Hour -ge $lstrptHr} | Where-Object {$_.'Is Teams' -eq '1' -or $_.'Is Teams' -eq $IsTeamsEnabled}
}
$AppShrngStrmsOutput | 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){
    $AppSharingStreamCount=0
    $AppSharingPoorDueToSpoiledTilePercentTotalCount=0
    $AppSharingPoorDueToRelativeOneWayAverageCount=0
    $AppSharingPoorDueToRDPTileProcessingLatencyAverageCount=0
    $AppSharingPoorStreamCount=0
    $AppSharingGoodStreamCount=0
    $AppSharingUnclassifiedStreamCount=0
    $AppSharingPoorPercentage=0
    $AvgAppSharingSpoiledTilePercentTotal=0
    $AvgAppSharingRDPTileProcessingLatency=0
    $AvgRelativeOneWay=0
    $AvgRelativeOneWayMax=0

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

        $AppSharingPoorDueToSpoiledTilePercentTotalCountlist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'AppSharing Poor Due To SpoiledTilePercentTotal Count')  -and  $_.'AppSharing Poor Due To SpoiledTilePercentTotal Count' -ne 'NaN' -and $_.'AppSharing Poor Due To SpoiledTilePercentTotal' -eq 'TRUE' }
        $AppSharingPoorDueToSpoiledTilePercentTotalCount =($AppSharingPoorDueToSpoiledTilePercentTotalCountlist | Measure-Object "AppSharing Poor Due To SpoiledTilePercentTotal Count" -Sum | select Sum).Sum
        if($AppSharingPoorDueToSpoiledTilePercentTotalCount){
            $list=$AppSharingPoorDueToSpoiledTilePercentTotalCountlist | where-object {$_.'AppSharing Poor Due To SpoiledTilePercentTotal Count' -gt 0.0001 } | Sort-Object { $_."AppSharing Poor Due To SpoiledTilePercentTotal Count" -as [int] } -Descending | select -First 10
            foreach($in in $list){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAppSharingPoorDueToSpoiledTilePercentTotalCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference Id'  ~!~ $in.'AppSharing Poor Due To SpoiledTilePercentTotal Count'
            }
            $list=$null
        }
        else{ 
            $AppSharingPoorDueToSpoiledTilePercentTotalCount=0 
        }
        $AppSharingPoorDueToSpoiledTilePercentTotalCountlist=0

        $AppSharingPoorDueToRelativeOneWayAverageCountlist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'AppSharing Poor Due To RelativeOneWayAverage Count')  -and  $_.'AppSharing Poor Due To RelativeOneWayAverage Count' -ne 'NaN' -and $_.'AppSharing Poor Due To RelativeOneWayAverage' -eq 'TRUE'} 
        $AppSharingPoorDueToRelativeOneWayAverageCount =($AppSharingPoorDueToRelativeOneWayAverageCountlist | Measure-Object "AppSharing Poor Due To RelativeOneWayAverage Count" -Sum | select Sum).Sum
        if($AppSharingPoorDueToRelativeOneWayAverageCount){
            $list=$AppSharingPoorDueToRelativeOneWayAverageCountlist | where-object {$_.'AppSharing Poor Due To RelativeOneWayAverage Count' -gt 0.0001 } | Sort-Object { $_."AppSharing Poor Due To RelativeOneWayAverage Count" -as [int] } -Descending | select -First 10
            foreach($in in $list){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAppSharingPoorDueToRelativeOneWayAverageCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference Id' ~!~ $in.'AppSharing Poor Due To RelativeOneWayAverage Count'
            }
            $list=$null
        }
        else{ 
            $AppSharingPoorDueToRelativeOneWayAverageCount=0
        }
        $AppSharingPoorDueToRelativeOneWayAverageCountlist=$null

        $AppSharingPoorDueToRDPTileProcessingLatencyAverageCountlist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'AppSharing Poor Due To RDPTileProcessingLatencyAverage Count')  -and  $_.'AppSharing Poor Due To RDPTileProcessingLatencyAverage Count' -ne 'NaN' -and $_.'AppSharing Poor Due To RDPTileProcessingLatencyAverage' -eq 'TRUE' } 
        $AppSharingPoorDueToRDPTileProcessingLatencyAverageCount = ($AppSharingPoorDueToRDPTileProcessingLatencyAverageCountlist| Measure-Object "AppSharing Poor Due To RDPTileProcessingLatencyAverage Count" -Sum | select Sum).Sum
        if($AppSharingPoorDueToRDPTileProcessingLatencyAverageCount){
            $list=$AppSharingPoorDueToRDPTileProcessingLatencyAverageCountlist | where-object {$_.'AppSharing Poor Due To RDPTileProcessingLatencyAverage Count' -gt 0.0001 }  | Sort-Object { $_."AppSharing Poor Due To RDPTileProcessingLatencyAverage Count" -as [int] } -Descending | select -First 10
            foreach($in in $list){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAppSharingPoorDueToRDPTileProcessingLatencyAverageCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference Id'  ~!~ $in.'AppSharing Poor Due To RDPTileProcessingLatencyAverage Count'
            }
            $list=$null
        }
        else{ 
            $AppSharingPoorDueToRDPTileProcessingLatencyAverageCount=0 
        }
        $AppSharingPoorDueToRDPTileProcessingLatencyAverageCountlist=$null

        $AppSharingPoorStreamCountlist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'AppSharing Poor Stream Count')  -and  $_.'AppSharing Poor Stream Count' -ne 'NaN' -and $_.'ClassifiedPoorCall' -eq 'TRUE' } 
        $AppSharingPoorStreamCount = ($AppSharingPoorStreamCountlist | Measure-Object "AppSharing Poor Stream Count" -Sum | select Sum).Sum
        if($AppSharingPoorStreamCount){
            $list=$AppSharingPoorStreamCountlist | where-object {$_.'AppSharing Poor Stream Count' -gt 0.0001} | Sort-Object { $_."AppSharing Poor Stream Count" -as [int] } -Descending  | select -First 10
            foreach($in in $list){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddAppSharingPoorStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference Id' ~!~ $in.'AppSharing Poor Stream Count'
            }
            $list=$null
        }
        else{ 
            $AppSharingPoorStreamCount=0
        }
        $AppSharingPoorStreamCountlist=$null

        $AppSharingGoodStreamCountlist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'AppSharing Good Stream Count')  -and  $_.'AppSharing Good Stream Count' -ne 'NaN' } 
        $AppSharingGoodStreamCount = ($AppSharingGoodStreamCountlist | Measure-Object "AppSharing Good Stream Count" -Sum | select Sum).Sum
        if(-not $AppSharingGoodStreamCount){
            $AppSharingGoodStreamCount =0
        }
        $AppSharingGoodStreamCountlist=$null

        $AppSharingUnclassifiedStreamCountlist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'AppSharing Unclassified Stream Count')  -and  $_.'AppSharing Unclassified Stream Count' -ne 'NaN' } 
        $AppSharingUnclassifiedStreamCount =($AppSharingUnclassifiedStreamCountlist | Measure-Object "AppSharing Unclassified Stream Count" -Sum | select Sum).Sum
        if(-not $AppSharingUnclassifiedStreamCount){
            $AppSharingUnclassifiedStreamCount =0
        } 
        $AppSharingUnclassifiedStreamCountlist=$null

        write-host '*********** AppSharingPoorPercentage measure **************'
        #$AppSharingPoorPercentagelist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'AppSharing Poor Percentage')  -and  $_.'AppSharing Poor Percentage' -ne 'NaN' -and $_.'AppSharing Poor Percentage' -gt 0.0001} 
        #$AppSharingPoorPercentage = ($AppSharingPoorPercentagelist | Measure-Object "AppSharing Poor Percentage" -Average | select Average).Average
        $AppSharingPoorPercentage = ($AppSharingPoorStreamCount/$AppSharingStreamCount)*100
        if(-not $AppSharingPoorPercentage) { $AppSharingPoorPercentage =0 } else { $AppSharingPoorPercentage=$AppSharingPoorPercentage.ToString("#.##") }
        $AppSharingPoorPercentagelist=$null

        $AvgAppSharingSpoiledTilePercentTotallist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg AppSharing Spoiled Tile Percent Total')  -and  $_.'Avg AppSharing Spoiled Tile Percent Total' -ne 'NaN' -and $_.'Avg AppSharing Spoiled Tile Percent Total' -gt 0.0001 } 
        $AvgAppSharingSpoiledTilePercentTotal = ($AvgAppSharingSpoiledTilePercentTotallist | Measure-Object "Avg AppSharing Spoiled Tile Percent Total" -Average | select Average).Average
        if( -not $AvgAppSharingSpoiledTilePercentTotal) { $AvgAppSharingSpoiledTilePercentTotal=0 } else { $AvgAppSharingSpoiledTilePercentTotal=$AvgAppSharingSpoiledTilePercentTotal.ToString("#.##") }
        $AvgAppSharingSpoiledTilePercentTotallist=$null

        $AvgAppSharingRDPTileProcessingLatencylist =$AppShrngStrmsOutput  | where-object { -not [string]::IsNullOrEmpty($_.'Avg AppSharing RDP Tile Processing Latency')  -and  $_.'Avg AppSharing RDP Tile Processing Latency' -ne 'NaN' -and $_.'Avg AppSharing RDP Tile Processing Latency' -gt 0.0001 } 
        $AvgAppSharingRDPTileProcessingLatency = ($AvgAppSharingRDPTileProcessingLatencylist | Measure-Object "Avg AppSharing RDP Tile Processing Latency" -Average | select Average).Average
        if( -not $AvgAppSharingRDPTileProcessingLatency) { $AvgAppSharingRDPTileProcessingLatency=0 }  else { $AvgAppSharingRDPTileProcessingLatency=$AvgAppSharingRDPTileProcessingLatency.ToString("#.##") }
        $AvgAppSharingRDPTileProcessingLatencylist=0

        $AvgRelativeOneWaylist =$AppShrngStrmsOutput | where-object { -not [string]::IsNullOrEmpty($_.'Avg Relative OneWay')  -and  $_.'Avg Relative OneWay' -ne 'NaN' -and $_.'Avg Relative OneWay' -gt 0.0001 }
        $AvgRelativeOneWay = ($AvgRelativeOneWaylist  | Measure-Object "Avg Relative OneWay" -Average | select Average).Average
        if(-not $AvgRelativeOneWay){ $AvgRelativeOneWay =0 }  else { $AvgRelativeOneWay=$AvgRelativeOneWay.ToString("#.##") }
        $AvgRelativeOneWaylist=$null

        $AvgRelativeOneWayMaxlist =$AppShrngStrmsOutput | where-object { -not [string]::IsNullOrEmpty($_.'Avg Relative OneWay Max')  -and  $_.'Avg Relative OneWay Max' -ne 'NaN' -and $_.'Avg Relative OneWay Max' -gt 0.0001 } 
        $AvgRelativeOneWayMax = ($AvgRelativeOneWayMaxlist | Measure-Object "Avg Relative OneWay Max" -Average | select Average).Average
        if( -not $AvgRelativeOneWayMax ){ $AvgRelativeOneWayMax =0 } else { $AvgRelativeOneWayMax=$AvgRelativeOneWayMax.ToString("#.##") }
        $AvgRelativeOneWayMaxlist=$null

        Write-Host 'measures##' $AppSharingStreamCount ~ $AppSharingPoorDueToSpoiledTilePercentTotalCount ~ $AppSharingPoorDueToRelativeOneWayAverageCount ~ $AppSharingPoorDueToRDPTileProcessingLatencyAverageCount ~ $AppSharingPoorStreamCount ~ $AppSharingGoodStreamCount ~ $AppSharingUnclassifiedStreamCount ~ $AppSharingPoorPercentage ~ $AvgAppSharingSpoiledTilePercentTotal ~ $AvgAppSharingRDPTileProcessingLatency ~ $AvgRelativeOneWay ~ $AvgRelativeOneWayMax 
    }
}
