clear 
[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

$TestInputs=$args
$reportingname='EXO\'+$TestInputs[0]

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

$ContactArr="MailContact","MailUser","GuestMailUser"
$states = @{}
$Groupcnt=0
$Contactcnt=0
$pubfoldrcnt=0

foreach($Recipnt in $Recip){
    if($Recipnt.RecipientTypeDetails -match 'Group'){
		$Groupcnt++
	}
	elseif($Recipnt.RecipientTypeDetails -match 'PublicFolder')
	{
		$pubfoldrcnt++
	}
	elseif($ContactArr -contains $Recipnt.RecipientTypeDetails){
		$Contactcnt++
	}
    else{
        
	    $myObj= $Mailboxstatimport |Select-Object -First 1
        $tstProps=[bool]($myObj.PSobject.Properties.name -match "PrimarySmtpAddress")
        if($tstProps){
		    $Mailboxstat= $Mailboxstatimport |Where-Object {$_.PrimarySmtpAddress -eq $Recipnt.PrimarySmtpAddress}
        }else{
            $Mailboxstat= $Mailboxstatimport |Where-Object {$_.UserPrincipalName -eq $Recipnt.PrimarySmtpAddress}
        }
	    if($Mailboxstat -ne $null){          
		    if($tstProps){        
				$totalSize= [String]$Mailboxstat.totalItemSize
				$resBytes= [double]$totalSize.Split('(')[1].Split(' ')[0].Trim().Replace(“,”,””)
				$resBytes= [math]::round($resBytes /1GB, 4)
			    if($states.ContainsKey($Recipnt.RecipientTypeDetails)){
					$tmpArray=$states[$Recipnt.RecipientTypeDetails]
					$tmpArray[0]+=1
					$tmpArray[1]+=$resBytes
                    if($Mailboxstat.ItemCount.GetType().toString() -eq 'System.Object[]'){
                        $tmpArray[2]+=$Mailboxstat.ItemCount[0]
                    }
                    else{
                        $tmpArray[2]+=$Mailboxstat.ItemCount
                    }
                }else{
				    [double[]]$myArray =1,$resBytes,$Mailboxstat.ItemCount
					$states.add($Recipnt.RecipientTypeDetails,$myArray)
                }
            }else{
                $totalSize= [String]$Mailboxstat.StorageUsed
				$resBytes= [math]::round($totalSize /1GB, 4)
			    if($states.ContainsKey($Recipnt.RecipientTypeDetails)){
					$tmpArray=$states[$Recipnt.RecipientTypeDetails]
					$tmpArray[0]+=1
					$tmpArray[1]+=$resBytes
                    if($Mailboxstat.ItemCount.GetType().toString() -eq 'System.Object[]'){
                        $tmpArray[2]+=$Mailboxstat.ItemCount[0]
                    }
                    else{
                        $tmpArray[2]+=$Mailboxstat.ItemCount
                    }
                }else{
				    [double[]]$myArray =1,$resBytes,$Mailboxstat.ItemCount
					$states.add($Recipnt.RecipientTypeDetails,$myArray)
                }

            }
        }
        else{
            if($Recipnt.RecipientTypeDetails -notmatch 'UserMailbox'){
                if($states.ContainsKey($Recipnt.RecipientTypeDetails)){
                    $tmpArray=$states[$Recipnt.RecipientTypeDetails]
                    $tmpArray[0]+=1
                }else{
                    [double[]]$myArray =1,-5,-5
                    $states.add($Recipnt.RecipientTypeDetails,$myArray)
                }
            }
        }
    }
}

if($Groupcnt -gt 0){
    Write-Host '# Group ~'$Groupcnt'~ -5 ~ -5'
}
if($Contactcnt -gt 0){
    Write-Host '# Contact~'$Contactcnt'~ -5 ~ -5'
}
if($pubfoldrcnt -gt 0){
    Write-Host '# PublicFolder~'$pubfoldrcnt'~ -5 ~ -5'
}   
foreach($keys in $states.Keys){   
    $val=$states[$Keys][1].tostring("#.##").replace(',','.')
    if($val -eq $null -or $val -eq ""){
	    $val=0
    }
    Write-Host '#'$keys '~'$states[$Keys][0]'~' $val '~' $states[$Keys][2] 
}

