$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
$PSDefaultParameterValues = @{'*:Encoding' = 'utf8'}

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egurkhaPath=($scriptPath.Substring(0,$scriptPath.ToLower().IndexOf('egurkha')+7)).Trim()
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy
clear

$testargs=$args
$rptTopNDD=[int]$testargs[0]
$reportingname='EXO\'+$testargs[1]
$showUsrRuleMails=$testargs[2]
$userName=$testargs[3]

$langPath=$egurkhaPath+'\agent\config\O365_lang.ini'
$encTyp=Eg-GetINIContent -Path $langPath -Subject 'File_Type' -Key 'encoding'

Try{
    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "transportrules" -keyFileName "ktransportrules" -EgPath $egurkhaPath
    if($readfiles -ne $null -and [System.IO.File]::Exists($readfiles[1]) -eq 'True'){
        $datafile=$readfiles[1] -replace (".csv",".dat") 
        $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]
        $ruledetail= import-csv $csvfile -Encoding $encTyp
        Remove-Item $csvfile
        Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'transportrules' -InputFile $readfiles[3]
        Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'ktransportrules' -InputFile $readfiles[4]
        Write-Host 'ReadFile:'$readfiles[3]
    }
}
Catch{
    $errmsg=$_.Exception.Message
    Write-Error -Message $errmsg
}
    
[System.GC]::GetTotalMemory($true) | out-null

Try{
    $totObjCnt=0
    $totInboundCnt=0
    $totOutboundCnt=0
    $totUniqSendrCnt=0
    $totUniqReceivrCnt=0

    $srtRuleDtls=$ruledetail| Sort-Object -Property 'Date' -Descending
    $eventTypes=$srtRuleDtls | Select-Object -Property 'EventType' -Unique

    foreach($eventType in $eventTypes){
        Try{
            $type=$eventType.EventType

            $trnsprtObjs=$srtRuleDtls | Where-Object{$_.EventType -eq $type}
            
            $inboundObjs=$trnsprtObjs | Where-Object{$_.Direction -eq 'Inbound'}
            $outboundObjs=$trnsprtObjs | Where-Object{$_.Direction -eq 'Outbound'}
            $uniqSendrCnt=($trnsprtObjs | Select-Object -Property 'SenderAddress' -Unique).Count
            $uniqRecevrCnt=($trnsprtObjs | Select-Object -Property 'RecipientAddress' -Unique).count

            $resStr='#Measure~'+$type+'~'+$trnsprtObjs.Count+'~'+$inboundObjs.Count+'~'+$outboundObjs.Count+'~'+$uniqSendrCnt+'~'+$uniqRecevrCnt+'<!>'
            Write-Host $resStr

            $totObjCnt+=$trnsprtObjs.Count
            $totInboundCnt+=$inboundObjs.Count
            $totOutboundCnt+=$outboundObjs.Count
            $totUniqSendrCnt+=$uniqSendrCnt
            $totUniqReceivrCnt+=$uniqRecevrCnt

            $inbondDDObjs=$inboundObjs | Select-Object -First $rptTopNDD
            foreach($inDDObj in $inbondDDObjs){
                $inMsgId=$inDDObj.MessageId
                if($inMsgId.Length -gt 1999){
                    $inMsgId=$inMsgId.Substring(0,1995)+'...'
                }
                $TotInMsgSize=[math]::round($inDDObj.MessageSize /1Kb, 4)
                $inDDStr='DDIndound#~#'+$type+'#~#'+$inDDObj.Date+'~!~'+$inDDObj.Domain+'~!~'+$inDDObj.TransportRule+'~!~'+$inDDObj.Subject+'~!~'+$TotInMsgSize.tostring("#.##").replace(',','.')+'~!~'+$inDDObj.SenderAddress+'~!~'+$inDDObj.RecipientAddress+'~!~'+$inDDObj.Action+'~!~'+$inMsgId+'<!>'
                Write-Host $inDDStr
            }

            $outbondDDObjs=$outboundObjs | Select-Object -First $rptTopNDD
            foreach($outDDObj in $outbondDDObjs){
                $outMsgId=$outDDObj.MessageId
                if($outMsgId.Length -gt 1999){
                    $outMsgId=$outMsgId.Substring(0,1995)+'...'
                }
                $TotOutMsgSize=[math]::round($outDDObj.MessageSize /1Kb, 4)
                $outDDStr='DDOutbound#~#'+$type+'#~#'+$outDDObj.Date+'~!~'+$outDDObj.Domain+'~!~'+$outDDObj.TransportRule+'~!~'+$outDDObj.Subject+'~!~'+$TotOutMsgSize.tostring("#.##").replace(',','.')+'~!~'+$outDDObj.SenderAddress+'~!~'+$outDDObj.RecipientAddress+'~!~'+$outDDObj.Action+'~!~'+$outMsgId+'<!>'
                Write-Host $outDDStr
            }
        }
        Catch{
            $excepMsg1='[EXORuleDetails] Exception Occured in "Foreach loop" -- [Line Number] '+$_.InvocationInfo.ScriptLineNumber+' -- '+$_.Exception
            Write-Host $excepMsg1
        }
    }
    $totResStr='#Summary~'+$totObjCnt+'~'+$totInboundCnt+'~'+$totOutboundCnt+'~'+$totUniqSendrCnt+'~'+$totUniqReceivrCnt+'<!>'
    Write-Host $totResStr
}
Catch{
    $excepMsg2='[EXORuleDetails] Exception Occured in "Processing CSV " -- [Line Number] '+$_.InvocationInfo.ScriptLineNumber+' -- '+$_.Exception
    Write-Host $excepMsg2
}

[System.GC]::GetTotalMemory($true) | out-null