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.Total Stream Count','Measures.Total CDR Available Stream Count','Measures.Total Media Failed Stream Count','Measures.Total Call Setup Failed Stream Count','Measures.Total Call Dropped Stream Count','Measures.Total Media Succeeded Stream Count','Measures.Total Call Setup Succeeded Stream Count','Measures.Total Call Setup Failure Percentage','Measures.Total Call Dropped Failure Percentage','Measures.Total Answer Seizure Ratio','Measures.Total Short Call Percentage','Measures.Total Media Failure Percentage','Measures.Avg Call Duration','Measures.Media Failed Due To Firewall DPI Stream Count','Measures.Firewall DPI Media Failure Percentage','Measures.Media Failed Due To Firewall IP Blocked Stream Count','Measures.Firewall IP Blocked Media Failure Percentage','Measures.Media Failed Due To Other Stream Count','Measures.Other Media Failure Percentage'
$Dimentions ='AllStreams.Date','AllStreams.Hour','AllStreams.First IP Address','AllStreams.Second IP Address','AllStreams.Conference Id','AllStreams.Is Teams','AllStreams.First UPN','AllStreams.Second UPN'

$latestCalSummry=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
    $latestCalSummry+=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}
}
$latestCalSummry | 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){
    $toalStreamsCnt=0
    $TotalCDRAvailableStreamCount=0
    $TotalMediaFailedStreamCount=0
    $TotalCallSetupFailedStreamCount=0
    $TotalCallDroppedStreamCount=0
    $TotalMediaSucceededStreamCount=0
    $TotalCallSetupSucceededStreamCount=0
    $TotalCallSetupFailurePercentage=0
    $TotalCallDroppedFailurePercentage=0
    $TotalAnswerSeizureRatio=0
    $TotalShortCallPercentage=0
    $TotalMediaFailurePercentage=0
    $AvgCallDuration=0
    $MediaFailedDueToFirewallDPIStreamCount=0
    $FirewallDPIMediaFailurePercentage=0
    $MediaFailedDueToFirewallIPBlockedStreamCount=0
    $FirewallIPBlockedMediaFailurePercentage=0
    $MediaFailedDueToOtherStreamCount=0
    $OtherMediaFailurePercentage=0


    $toalStreamsCnt=($latestCalSummry | where-object { $_.'Total Stream Count' -ne 'NaN' } | Measure-Object "Total Stream Count" -Sum | select Sum).Sum
    if($toalStreamsCnt){
        $TotalCDRAvailableStreamCount=($latestCalSummry | where-object { $_.'Total CDR Available Stream Count' -ne 'NaN' } | Measure-Object "Total CDR Available Stream Count" -Sum | select Sum).Sum

        Write-Host '***************DD for TotalMediaFailedStreamCount Measure****************************'
        $TotalMediaFailedStreamCount=($latestCalSummry | where-object { $_.'Total Media Failed Stream Count' -ne 'NaN' } | Measure-Object "Total Media Failed Stream Count" -Sum | select Sum).Sum
        if($TotalMediaFailedStreamCount){
            $ddforFailedstreams = $latestCalSummry | Where-Object { $_."Total Media Failed Stream Count" -gt 0.001 } | Sort-Object { $_."Total Media Failed Stream Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddforFailedstreams){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddTotalMediaFailedStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address' ~!~ $in.'Conference Id' ~!~ $in.'Total Media Failed Stream Count'
            }
            $ddforFailedstreams=$null
        }

        Write-Host '***************DD for TotalCallSetupFailedStreamCount Measure****************************'
        $TotalCallSetupFailedStreamCount=($latestCalSummry  | where-object { $_.'Total Call Setup Failed Stream Count' -ne 'NaN' } | Measure-Object "Total Call Setup Failed Stream Count" -Sum | select Sum).Sum
        if($TotalCallSetupFailedStreamCount){
            $ddforTotalCalFiledstreams = $latestCalSummry | Where-Object { $_."Total Call Setup Failed Stream Count" -gt 0.001 } | Sort-Object { $_."Total Call Setup Failed Stream Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddforTotalCalFiledstreams){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddTotalCallSetupFailedStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address'  ~!~ $in.'Conference Id' ~!~ $in.'Total Call Setup Failed Stream Count'
            }
            $ddforTotalCalFiledstreams=$null
        }

        Write-Host '***************DD for TotalCallDroppedStreamCount Measure****************************'
        $TotalCallDroppedStreamCount=($latestCalSummry  | where-object { $_.'Total Call Dropped Stream Count' -ne 'NaN' } | Measure-Object "Total Call Dropped Stream Count" -Sum | select Sum).Sum
        if($TotalCallDroppedStreamCount){
            $ddforTotalCallDroppedStreamCount = $latestCalSummry | Where-Object { $_."Total Call Dropped Stream Count" -gt 0.001 } | Sort-Object { $_."Total Call Dropped Stream Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddforTotalCallDroppedStreamCount){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddTotalCallDroppedStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address'  ~!~ $in.'Conference Id' ~!~ $in.'Total Call Dropped Stream Count'
            }
            $ddforTotalCallDroppedStreamCount=$null
        }

        $TotalMediaSucceededStreamCount=($latestCalSummry | where-object { $_.'Total Media Succeeded Stream Count' -ne 'NaN' } | Measure-Object "Total Media Succeeded Stream Count" -Sum | select Sum).Sum
        $TotalCallSetupSucceededStreamCount=($latestCalSummry | where-object { $_.'Total Call Setup Succeeded Stream Count' -ne 'NaN' } | Measure-Object "Total Call Setup Succeeded Stream Count" -Sum | select Sum).Sum

        Write-Host '***************TotalCallSetupFailurePercentage Measure****************************'
        #$TotalCallSetupFailurePercentage=($latestCalSummry | where-object { $_.'Total Call Setup Failure Percentage' -ne 'NaN' -and $_."Total Call Setup Failure Percentage" -gt 0.001 } | Measure-Object "Total Call Setup Failure Percentage" -Average | select Average).Average
        $TotalCallSetupFailurePercentage=($TotalCallSetupFailedStreamCount/$toalStreamsCnt)*100
        if(-not $TotalCallSetupFailurePercentage){  $TotalCallSetupFailurePercentage=0 }  else { $TotalCallSetupFailurePercentage=$TotalCallSetupFailurePercentage.ToString("#.##") }

        Write-Host '***************TotalCallDroppedFailurePercentage Measure****************************'
        #$TotalCallDroppedFailurePercentage=($latestCalSummry | where-object { $_.'Total Call Dropped Failure Percentage' -ne 'NaN' -and $_."Total Call Dropped Failure Percentage" -gt 0.001 } | Measure-Object "Total Call Dropped Failure Percentage" -Average | select Average).Average
        $TotalCallDroppedFailurePercentage=($TotalCallDroppedStreamCount/$toalStreamsCnt)*100
        if(-not $TotalCallDroppedFailurePercentage){  $TotalCallDroppedFailurePercentage=0 }  else { $TotalCallDroppedFailurePercentage=$TotalCallDroppedFailurePercentage.ToString("#.##") }

        $TotalAnswerSeizureRatio=($latestCalSummry  | where-object { $_.'Total Answer Seizure Ratio' -ne 'NaN' } | Measure-Object "Total Answer Seizure Ratio" -Sum | select Sum).Sum

        Write-Host '***************TotalShortCallPercentage Measure************************************************'
        $totalshortcallcount=0
        $TotalShortCallPercentagelist=($latestCalSummry | where-object { $_.'Total Short Call Percentage' -ne 'NaN' -and $_."Total Short Call Percentage" -gt 0.001 } ) | Select-Object 'Total Stream Count','Total Short Call Percentage' #| Measure-Object "Total Short Call Percentage" -Average | select Average).Average
        foreach($input in $TotalShortCallPercentagelist){
            $totalshortcallcount=$totalshortcallcount+(([float]$input.'Total Short Call Percentage')*([float]$input.'Total Stream Count'))/100
        }
        $TotalShortCallPercentage=($totalshortcallcount/$toalStreamsCnt)*100
        if(-not $TotalShortCallPercentage){  $TotalShortCallPercentage=0 }  else { $TotalShortCallPercentage=$TotalShortCallPercentage.ToString("#.##") }

        Write-Host '***************TotalMediaFailurePercentage Measure****************************'
        <#
        $TotalMediaFailurePercentage=($latestCalSummry | where-object { $_.'Total Media Failure Percentage' -ne 'NaN' -and $_."Total Media Failure Percentage" -gt 0.001 } | Measure-Object "Total Media Failure Percentage" -Average | select Average).Average
        #>
        $TotalMediaFailurePercentage=($TotalMediaFailedStreamCount/$toalStreamsCnt)*100
        if(-not $TotalMediaFailurePercentage){  $TotalMediaFailurePercentage=0 }  else { $TotalMediaFailurePercentage=$TotalMediaFailurePercentage.ToString("#.##") }

        $AvgCallDuration=($latestCalSummry | where-object { $_.'Avg Call Duration' -ne 'NaN' -and $_."Avg Call Duration" -gt 0.001 } | Measure-Object "Avg Call Duration" -Average | select Average).Average
        if(-not $AvgCallDuration){  $AvgCallDuration=0 }  else { $AvgCallDuration=$AvgCallDuration.ToString("#.##") }

        Write-Host '***************DD for MediaFailedDueToFirewallDPIStreamCount Measure****************************'
        $MediaFailedDueToFirewallDPIStreamCount=($latestCalSummry | where-object { $_.'Media failed due to firewall DPI stream count' -ne 'NaN' } | Measure-Object "Media failed due to firewall DPI stream count" -Sum | select Sum).Sum
        if($MediaFailedDueToFirewallDPIStreamCount){
            $ddforMediaFailedDueToFirewallDPIStreamCount = $latestCalSummry | Where-Object { $_."Media failed due to firewall DPI stream count" -gt 0.001 } | Sort-Object { $_."Media failed due to firewall DPI stream count" -as [int] } -Descending | select -First 10
            foreach($in in $ddforMediaFailedDueToFirewallDPIStreamCount){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddMediaFailedDueToFirewallDPIStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address'  ~!~ $in.'Conference Id' ~!~ $in.'Media failed due to firewall DPI stream count'
            }
            $ddforMediaFailedDueToFirewallDPIStreamCount=$null
        }

        Write-Host '*************** FirewallDPIMediaFailurePercentage Measure****************************'
        #$FirewallDPIMediaFailurePercentage=($latestCalSummry  | where-object { $_.'Firewall DPI Media Failure Percentage' -ne 'NaN' -and $_."Firewall DPI Media Failure Percentage" -gt 0.001 } | Measure-Object "Firewall DPI Media Failure Percentage" -Average | select Average).Average
        $FirewallDPIMediaFailurePercentage=($MediaFailedDueToFirewallDPIStreamCount/$toalStreamsCnt)*100
        if(-not $FirewallDPIMediaFailurePercentage){  $FirewallDPIMediaFailurePercentage=0 }  else { $FirewallDPIMediaFailurePercentage=$FirewallDPIMediaFailurePercentage.ToString("#.##") }

        Write-Host '***************DD for MediaFailedDueToFirewallIPBlockedStreamCount Measure****************************'
        $MediaFailedDueToFirewallIPBlockedStreamCount=($latestCalSummry | where-object { $_.'Media Failed Due To Firewall IP Blocked Stream Count' -ne 'NaN' } | Measure-Object "Media Failed Due To Firewall IP Blocked Stream Count" -Sum | select Sum).Sum
        if($MediaFailedDueToFirewallIPBlockedStreamCount){
            $ddforMediaFailedDueToFirewallIPBlockedStreamCount = $latestCalSummry | Where-Object { $_."Media Failed Due To Firewall IP Blocked Stream Count" -gt 0.001 } | Sort-Object { $_."Media Failed Due To Firewall IP Blocked Stream Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddforMediaFailedDueToFirewallDPIStreamCount){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddMediaFailedDueToFirewallIPBlockedStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address'  ~!~ $in.'Conference Id' ~!~ $in.'Media Failed Due To Firewall IP Blocked Stream Count'
            }
            $ddforMediaFailedDueToFirewallIPBlockedStreamCount=$null
        }

        Write-Host '*************** FirewallIPBlockedMediaFailurePercentage Measure****************************'
        #$FirewallIPBlockedMediaFailurePercentage=($latestCalSummry  | where-object { $_.'Firewall IP Blocked Media Failure Percentage' -ne 'NaN' -and $_."Firewall IP Blocked Media Failure Percentage" -gt 0.001 } | Measure-Object "Firewall IP Blocked Media Failure Percentage" -Average | select Average).Average
        $FirewallIPBlockedMediaFailurePercentage=($MediaFailedDueToFirewallIPBlockedStreamCount/$toalStreamsCnt)*100
        if(-not $FirewallIPBlockedMediaFailurePercentage){  $FirewallIPBlockedMediaFailurePercentage=0 }  else { $FirewallIPBlockedMediaFailurePercentage=$FirewallIPBlockedMediaFailurePercentage.ToString("#.##") }

        Write-Host '***************DD for MediaFailedDueToOtherStreamCount Measure****************************'
        $MediaFailedDueToOtherStreamCount=($latestCalSummry | where-object { $_.'Media Failed Due To Other Stream Count' -ne 'NaN' } | Measure-Object "Media Failed Due To Other Stream Count" -Sum | select Sum).Sum
        if($MediaFailedDueToOtherStreamCount){
            $ddforMediaFailedDueToOtherStreamCount = $latestCalSummry | Where-Object { $_."Media Failed Due To Other Stream Count" -gt 0.001 } | Sort-Object { $_."Media Failed Due To Other Stream Count" -as [int] } -Descending | select -First 10
            foreach($in in $ddforMediaFailedDueToOtherStreamCount){
                $ltimArr=Get-LocalTime -dat $in.Date -hr $in.Hour
                Write-Host 'ddMediaFailedDueToOtherStreamCount#' $ltimArr[0] ~!~ $ltimArr[1] ~!~ $in.'First UPN' ~!~ $in.'Second UPN' ~!~ $in.'First IP Address' ~!~ $in.'Second IP Address'  ~!~ $in.'Conference Id' ~!~ $in.'Media Failed Due To Other Stream Count'
            }
            $ddforMediaFailedDueToOtherStreamCount=$null
        }

        Write-Host '*************** OtherMediaFailurePercentage Measure****************************'
        #$OtherMediaFailurePercentage=($latestCalSummry | where-object { $_.'Other Media Failure Percentage' -ne 'NaN' -and $_."Other Media Failure Percentage" -gt 0.001 } | Measure-Object "Other Media Failure Percentage" -Average | select Average).Average
        $OtherMediaFailurePercentage=($MediaFailedDueToOtherStreamCount/$toalStreamsCnt)*100
        if(-not $OtherMediaFailurePercentage){  $OtherMediaFailurePercentage=0 }  else { $OtherMediaFailurePercentage=$OtherMediaFailurePercentage.ToString("#.##") }
    }
    Write-Host 'measures##' $toalStreamsCnt ~$TotalCDRAvailableStreamCount ~ $TotalMediaFailedStreamCount ~ $TotalCallSetupFailedStreamCount ~ $TotalCallDroppedStreamCount ~ $TotalMediaSucceededStreamCount ~ $TotalCallSetupSucceededStreamCount ~ $TotalCallSetupFailurePercentage ~ $TotalCallDroppedFailurePercentage ~ $TotalAnswerSeizureRatio ~ $TotalShortCallPercentage ~ $TotalMediaFailurePercentage ~ $AvgCallDuration ~ $MediaFailedDueToFirewallDPIStreamCount ~ $FirewallDPIMediaFailurePercentage ~ $MediaFailedDueToFirewallIPBlockedStreamCount ~ $FirewallIPBlockedMediaFailurePercentage ~ $MediaFailedDueToOtherStreamCount ~ $OtherMediaFailurePercentage
}









