[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value
$egurkhaPath=$egInstallpath.Value.ToString()
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy

clear

$InEvnType= @{}
$OutEvnType= @{}
$InEvnTypeCnt= @{}
$OutEvnTypeCnt= @{}
$InEvnSenSize= @{}
$OutEvnSenSize= @{}
$InSendEvnType= @{}
$OutSendEvnType= @{}
$InEvnSize= @{}
$OutEvnSize= @{}
$UniqSen= @{}
$UniqRec= @{}
$EvnType= New-Object System.Collections.ArrayList

$testargs=$args

$reportingname='EXO\'+$testargs[0]
$showUsrSpamMails=$testargs[1]
$userName=$testargs[2]
$startTime=$testargs[3]
$startTime=$startTime.Replace('_',' ')
try{
    $CultureDateTimeFormat = (Get-Culture).DateTimeFormat
    $DateFormat = $CultureDateTimeFormat.ShortDatePattern
    $TimeFormat = $CultureDateTimeFormat.LongTimePattern
    $DateTimeFormat = "$DateFormat $TimeFormat"

    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "spam" -keyFileName "kspam" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]
    $spamdetail= import-csv $csvfile
    Remove-Item $csvfile
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'spam' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kspam' -InputFile $readfiles[4]
    Write-Host 'ReadFile:'$readfiles[3]
    }
    catch [System.Management.Automation.RuntimeException] {
        Write-Error -Message "File not found. The $reportingname location does not contain spam files."
    }
    catch{
        $errmsg=$_.Exception.Message
        $errstack=$_.Exception.StackTrace
        Write-Error -Message $errmsg
    }


    $spamdetail=  $spamdetail  | Sort-Object {[DateTime]::ParseExact($_.'Date',$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)}  -Descending
	$LastDateSpam=$spamdetail|select -Property Date -First 1    
	$TotInboundSize=0
	$TotOutboundSize=0
	$reg="^\d*/\d*/[2-9]\d\d\d \d*:\d*:\d*$"

if($spamdetail -ne $null){
	foreach($spamdata in $spamdetail){
            $entryflg=$false
            if($startTime -ne $null -and $startTime -ne ''){
               $spamDate = [DateTime]::ParseExact($spamdata.Date,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
               $prevTime = [DateTime]::ParseExact($startTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
                if($spamDate -gt $prevTime){
                    $entryflg=$true
                }
            }
            else{
                $entryflg=$true
            }
            if($entryflg){
            
            if(!$showUsrSpamMails)
            {
                if( ($spamdata.SenderAddress).toString().toLower().trim() -eq $userName.toString().toLower().trim() -or ($spamdata.RecipientAddress).toString().toLower().trim() -eq $userName.toString().toLower().trim() )
                {
                    continue;
                }
            }  
			$TotMsgSizemb=[math]::round($spamdata.MessageSize /1mb, 4)
            $TotMsgSizegb=[math]::round($spamdata.MessageSize /1gb, 4)
			if(-not $EvnType.Contains($spamdata.EventType)){
			$EvnType.Add($spamdata.EventType)
		    }
            $totMsgSizeky=$spamdata.EventType+'~'+$spamdata.SenderAddress+'~!~'+$spamdata.RecipientAddress
            $EvnTypeky=$spamdata.SenderAddress+'~!~'+$spamdata.RecipientAddress
		    if($spamdata.Direction -eq 'Inbound'){       
			    if($InEvnType.Contains($spamdata.EventType)){
                     $InEvnTypeCnt[$spamdata.EventType]+=1
                     $tmposht=$InEvnType[$spamdata.EventType]
			            if($tmposht.Contains($EvnTypeky)){
                            $tmposht[$EvnTypeky]+=$TotMsgSizemb
                        }
                        else{
                            $tmposht.Add($EvnTypeky,$TotMsgSizemb)
                        }
                }
                else{
                     $InEvnTypeCnt.Add($spamdata.EventType,1)   
                     $InSendEvnType.Add($EvnTypeky,1)       
			         $InEvnType.Add($spamdata.EventType,$InSendEvnType)
			    }
			    if($InEvnSize.Contains($spamdata.EventType)){
				    $InEvnSize[$spamdata.EventType]+=$TotMsgSizegb 
			    }else{
			        $InEvnSize.Add($spamdata.EventType,$TotMsgSizegb)
			    }
			    if($InEvnSenSize.Contains($totMsgSizeky)){
				    $InEvnSenSize[$totMsgSizeky]+=1 
			    }else{
			        $InEvnSenSize.Add($totMsgSizeky,1)
			    }
		    }
            else{
			    if($OutEvnType.Contains($spamdata.EventType)){
                        $OutEvnTypeCnt[$spamdata.EventType]+=1
                     $tmposht=$OutEvnType[$spamdata.EventType]
			            if($tmposht.Contains($EvnTypeky)){
                            $tmposht[$EvnTypeky]+=$TotMsgSizemb
                        }
                        else{
                            $tmposht.Add($EvnTypeky,$TotMsgSizemb)
                        }
                }
                else{
                     $OutEvnTypeCnt.Add($spamdata.EventType,1)
                     $OutSendEvnType.Add($EvnTypeky,1)       
			         $OutEvnType.Add($spamdata.EventType,$OutSendEvnType)
			    }

			    if($OutEvnSize.Contains($spamdata.EventType)){
				    $OutEvnSize[$spamdata.EventType]+=$TotMsgSizegb
			    }else{
				    $OutEvnSize.Add($spamdata.EventType,$TotMsgSizegb)
			    }
                if($OutEvnSenSize.Contains($totMsgSizeky)){
				    $OutEvnSenSize[$totMsgSizeky]+=1
			    }else{
				    $OutEvnSenSize.Add($totMsgSizeky,1)
			    }
		    }
		if($UniqSen.Contains($spamdata.EventType)){
			$tmpSenAdd=$UniqSen[$spamdata.EventType]
			$tmpRecAdd=$UniqRec[$spamdata.EventType]
			if($tmpSenAdd.Contains($spamdata.SenderAddress)){
				$tmpSenAdd[$spamdata.SenderAddress]+=1
			}else{
				$tmpSenAdd.Add($spamdata.SenderAddress,1)
			}
			if($tmpRecAdd.Contains($spamdata.RecipientAddress)){
				$tmpRecAdd[$spamdata.RecipientAddress]+=1
			}else{
				$tmpRecAdd.Add($spamdata.RecipientAddress,1)
			}
		    }
		    else{
			$SndAdd= @{}
			$RecAdd= @{}
			$SndAdd.Add($spamdata.SenderAddress,1)
			$RecAdd.Add($spamdata.RecipientAddress,1)
			$UniqSen.Add($spamdata.EventType,$SndAdd)
			$UniqRec.Add($spamdata.EventType,$RecAdd)
		    }
	    }
	    }

	    clear     
  
foreach($Evntkeys in $EvnType){	
    $inEvntcnt=0
    $outEvntcnt=0
    $inEvntsz=0
    $outEvntsz=0
    $evntlist=$InEvnType[$Evntkeys]
    $Outevntlist=$OutEvnType[$Evntkeys]
    $uniQSendrs=$UniqSen[$Evntkeys]
    $uniQRecrs=$UniqRec[$Evntkeys]
    #  $evntlist.keys | sort { $evntlist.$_ } -des | foreach {  Write-host $_ '~' $evntlist.$_ '~' $InEvnSize[$Evntkeys+'~'+$_].tostring("#.##") } | Select-Object -First 20
    if($evntlist -ne $null){
        $in =$evntlist.keys | sort { $evntlist.$_ } -des | Select-Object -First 10
        foreach($inky in $in) {
            Write-host '# DDSpam In' $Evntkeys '!' $inky  '~!~' $evntlist[$inky].tostring("#.##").replace(',','.')     '~!~' $InEvnSenSize[$Evntkeys+'~'+$inky] 
        }
        $inEvntcnt=$InEvnTypeCnt[$Evntkeys]
        $inEvntsz=$InEvnSize[$Evntkeys].tostring("#.##").replace(',','.')
    }
                
    if($Outevntlist -ne $null){            
        $out =$Outevntlist.keys | sort { $Outevntlist.$_ } -des | Select-Object -First 10
        foreach($outky in $out) {
            Write-host '# DDSpam Out'$Evntkeys '!' $outky '~!~' $outevntlist[$outky].tostring("#.##").replace(',','.') '~!~' $OutEvnSenSize[$Evntkeys+'~'+$outky]
        }
        $outEvntcnt=$OutEvnTypeCnt[$Evntkeys]
        $outEvntsz=$OutEvnSize[$Evntkeys].tostring("#.##").replace(',','.')
    }
    if($uniQSendrs -ne $null){            
        $snds =$uniQSendrs.keys | sort { $uniQSendrs.$_ } -des | Select-Object -First 10
        foreach($sndsky in $snds) {
            Write-host '# DDUniqueSenders'$Evntkeys '!' $sndsky '~!~' $uniQSendrs[$sndsky]
        }
        $outEvntcnt=$OutEvnTypeCnt[$Evntkeys]
        $outEvntsz=$OutEvnSize[$Evntkeys].tostring("#.##").replace(',','.')
    } 
    if($uniQRecrs -ne $null){            
        $recrs =$uniQRecrs.keys | sort { $uniQRecrs.$_ } -des | Select-Object -First 10
        foreach($recrsky in $recrs) {
            Write-host '# DDUniqueRecievers'$Evntkeys '!' $recrsky '~!~' $uniQRecrs[$recrsky]
        }
        $outEvntcnt=$OutEvnTypeCnt[$Evntkeys]
        $outEvntsz=$OutEvnSize[$Evntkeys].tostring("#.##").replace(',','.')
    } 
    Write-Host '#Measure' $Evntkeys '~' $inEvntcnt '~' $outEvntcnt '~' $inEvntsz '~' $outEvntsz '~' $UniqSen[$Evntkeys].Count'~'$UniqRec[$Evntkeys].Count
}
 Write-Host 'LastDate:'$LastDateSpam.Date.Replace(' ','_')
 Write-Host 'ReadFile:'$readfiles[3]
}
   
