
clear
[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"
Import-Module $egEncryPath,$egDatnKy -WarningAction SilentlyContinue

#<#
$TestInputs=$args
$username=$TestInputs[0]
$password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyUser=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$proxyserver=$TestInputs[4]
$readDat=[DateTime]$TestInputs[5]
$rptTopNDD=[int]$TestInputs[6]
#>

$ToReadDate=$readDat.tostring(“yyyy-MM-dd”)
$o365Domain=Eg-GetDomain -userName $username -Password $password -proxyUsr $proxyUser -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver
Function Eg-InvokeUrl(){
	[CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=1)]
        [String]$Url
    )
    Process
    {
        $creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $appId, $appSecret
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"-ArgumentList $authString
        $context = $authContext.AcquireTokenAsync($resource, $creds).Result
        $authCode=$context.CreateAuthorizationHeader()

        $header = @{
            'Authorization'=$authCode
        }
        $queryRes = Invoke-RestMethod -Method 'Get' -Headers $header -Uri $Url
        $queryRes=$queryRes.Replace('ï»¿','')
        $queryRes=$queryRes.Replace('(Byte)','')
        $queryRes=$queryRes.Replace(' ','')
        $resultarray = ConvertFrom-Csv -InputObject $queryRes
        $reprts=$resultarray | ConvertTo-Json 
        $jsonreprt=@()
        $jsonreprt='{ "Usage" :['+$reprts+']}'
        $reports=$jsonreprt | ConvertFrom-Json
        return $reports.Usage
    }
}

#------Get App Reg Details ------------
$GraphDir=$egurkhaPath+'\agent\O365\MsGraph'
$unProtPath=$GraphDir+'\GraphDetails.dat'
$keyFileNam='\GraphDetailsKey.dat'
$kvalue=Get-Content -Path $GraphDir$keyFileNam
$null=Unprotect-File $unProtPath -Algorithm AES -KeyAsPlainText $kvalue -DstSuffix '.ini'
$spoGraphDtls=$GraphDir+"\GraphDetails.ini"
$getInputs=Get-Content -Path $spoGraphDtls
Remove-Item $spoGraphDtls
$flag=$false
foreach($input in $getInputs){
    if($input.StartsWith('[') -and $input.ToLower().Contains($o365Domain.ToLower())){
        $flag=$true
    }
    if($flag){
        if($input.Contains("client_id")){
            $appId=$input.ToString().Substring($input.IndexOf('~')+1)
        }
        if($input.Contains("client_secret")){
            $appSecret=$input.ToString().Substring($input.IndexOf('~')+1)
        }
        if($input.Contains("TenantName")){
            $tenantID=$input.ToString().Substring($input.IndexOf('~')+1)
        }
        if($input.Contains("Authority")){
            $authString=$input.ToString().Substring($input.IndexOf('~')+1)
            $authString=$authString+$o365Domain
        }
        if($input.Contains("Resource")){
            $resource=$input.ToString().Substring($input.IndexOf('~')+1)
            $flag=$false
        }
    }         
}

$path=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
Add-Type -Path $path

$emailActurl= "https://graph.microsoft.com/v1.0/reports/getEmailActivityUserDetail(period='D7')"
$actUsrDtls=Eg-InvokeUrl -Url $emailActurl

if($actUsrDtls -ne $null -and $actUsrDtls -ne ''){
    $rptDat=$actUsrDtls | select -First 1
    $rptDat=$rptDat.ReportRefreshDate.ToString().Trim()
    if([DateTime]$rptDat -ge [DateTime]$ToReadDate){
        Write-Host 'ReadedDate for the Date#'$rptDat
        $totSent=0;$totReceiv=0;$totRead=0;$i=0
        $actUsrDtls |Where-Object{$_.IsDeleted -eq $false} |Sort-Object { $_.SendCount -as [int] } -Descending |ForEach-Object{
            $totSent+=$_.SendCount;
            $totReceiv+=$_.ReceiveCount;
            $totRead+=$_.ReadCount;
            if($i -lt $rptTopNDD){
                $top10Send='Top10Senders#'+$_.ReportRefreshDate+'~!~'+$_.UserPrincipalName+'~!~'+$_.DisplayName+'~!~'+$_.LastActivityDate+'~!~'+$_.SendCount+'~!~'+$_.ReceiveCount+'~!~'+$_.ReadCount+'~!~'+$_.AssignedProducts
                Write-Host $top10Send
                $i++
            }
        }
        $actUsrDtls |Where-Object{$_.IsDeleted -eq $false} |Sort-Object { $_.ReceiveCount -as [int] } -Descending | select -First $rptTopNDD |ForEach-Object{ 
            $top10Receivrs='Top10Receivrs#'+$_.ReportRefreshDate+'~!~'+$_.UserPrincipalName+'~!~'+$_.DisplayName+'~!~'+$_.LastActivityDate+'~!~'+$_.SendCount+'~!~'+$_.ReceiveCount+'~!~'+$_.ReadCount+'~!~'+$_.AssignedProducts
            Write-Host $top10Receivrs
        }
        $measures='Measures#'+$totSent+'~'+$totReceiv+'~'+$totRead
        Write-Host $measures  
    } 
}



