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]
$rptNam=$TestInputs[6]


$toReadDat=$readDat.tostring(“yyyy-MM-dd”)
$rptPath=$egurkhaPath+'\agent\ODB\'+$rptNam
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

$domainVal=Eg-GetDomain -userName $username -Password $password -proxyUsr $proxyUser -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver

$azureVal=Eg-GetAzureEnv -UserName $username -subject 'O365_Graph'
$azureEnvArr=$azureVal.Split(',')

$clientArr=Get-GraphClientSecret -InitialDomain $domainVal
if($clientArr -ne $null){
    $clientId=$clientArr[0].ToString().Trim()
    $clientSecret=$clientArr[1].ToString().Trim()
}
$authStr=$azureEnvArr[0].ToString().Trim()+$domainVal
$resourceStr=$azureEnvArr[1].ToString().Trim()
$path=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
Add-Type -Path $path

Function Eg-InvokeUrl(){
	[CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=1)]
        [String]$Url, 
        [Parameter(Mandatory=$true, Position=2)]
        [String]$Method,
        [Parameter(Mandatory=$true, Position=3)]
        [String]$PropsVal,
        [Parameter(Mandatory=$true, Position=4)]
        [String]$filePath       
    )

    Process
    {
        $creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $clientId, $clientSecret
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"-ArgumentList $authStr
        $context = $authContext.AcquireTokenAsync($resourceStr, $creds).Result
        $authCode=$context.CreateAuthorizationHeader()
        $header = @{
            'Authorization'=$authCode
        }

        $query = Invoke-RestMethod -Method $Method -Headers $header -Uri $Url
        $query=$query.Replace('ï»¿','')
        $query=$query.Replace(' ','')

        $resultarray = ConvertFrom-Csv -InputObject $query
        $reprts=$resultarray | ConvertTo-Json 
        $jsonreprt=@()
        $jsonreprt='{ "Usage" :['+$reprts+']}'
        $reports=$jsonreprt | ConvertFrom-Json
        $psobje=''
        for($i=0;$i -lt $reports.Usage.Length ;$i++ ){   
           $reports.Usage[$i] |Sort-Object -Property $PropsVal -Descending |Export-Csv $filePath -Append -NoTypeInformation -Force
        }
    }
}
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$ODBFileCnts=$rptPath+'\ODBActFileCounts'+$timenow+'.csv'
$ODBUsrCnts=$rptPath+'\ODBActUserCounts'+$timenow+'.csv'
$ODBActUsr=$rptPath+'\ODBActUsr'+$timenow+'.csv'

$url1="https://graph.microsoft.com/v1.0/reports/getOneDriveActivityFileCounts(period='D7')"
$url2="https://graph.microsoft.com/v1.0/reports/getOneDriveActivityUserCounts(period='D7')"
$url3="https://graph.microsoft.com/v1.0/reports/getOneDriveActivityUserDetail(period='D7')"

Try{
    Eg-InvokeUrl -Url $url1 -Method 'Get' -PropsVal 'ReportDate' -filePath $ODBFileCnts
    Eg-InvokeUrl -Url $url2 -Method 'Get' -PropsVal 'ReportDate' -filePath $ODBUsrCnts
    Eg-InvokeUrl -Url $url3 -Method 'Get' -PropsVal 'LastActivityDate' -filePath $ODBActUsr

    $actFileCntsArr=Import-Csv $ODBFileCnts
    $actUsrCntsArr=Import-Csv $ODBUsrCnts
    $actUsrDtlsArr=Import-Csv $ODBActUsr


    $fileCntRptDat=$actFileCntsArr | select ReportRefreshDate -First 1
    $usrCntRptDat=$actUsrCntsArr | select ReportRefreshDate -First 1
    $actUsrRptDat=$actUsrDtlsArr | select ReportRefreshDate -First 1

    $fileCntRptDat=($fileCntRptDat.ReportRefreshDate)
    $usrCntRptDat=($usrCntRptDat.ReportRefreshDate)
    $actUsrRptDat=($actUsrRptDat.ReportRefreshDate)

    if([datetime]$fileCntRptDat -eq [datetime]$usrCntRptDat -eq [datetime]$actUsrRptDat){
        if([datetime]$actUsrRptDat -ge [datetime]$toReadDat){
            Write-Host 'ReadedDate for the Date#'$actUsrRptDat
            $fetchDate=$true
            $rptDate=''
            $fileVieworEdit='';$filesynced='';$fileShareIntern='';$fileShareExtern='';
            foreach($actFileCnts in $actFileCntsArr){
                if($fetchDate){
                    $rptDate=$actFileCnts.ReportDate
                }
                $fetchDate=$false
                if($rptDate -eq $actFileCnts.ReportDate){
                    if($actFileCnts.ViewedOrEdited -ne ''){$fileVieworEdit=$actFileCnts.ViewedOrEdited}else{$fileVieworEdit=0}
                    if($actFileCnts.Synced -ne ''){$filesynced=$actFileCnts.Synced}else{$filesynced=0}
                    if($actFileCnts.SharedInternally -ne ''){$fileShareIntern=$actFileCnts.SharedInternally}else{$fileShareIntern=0}
                    if($actFileCnts.SharedExternally -ne ''){$fileShareExtern=$actFileCnts.SharedExternally}else{$fileShareExtern=0}
                }
            }
            $totalOper=[int]$fileVieworEdit+[int]$filesynced+[int]$fileShareIntern+[int]$fileShareExtern
            $fileRpt=[String]$totalOper+'~'+$fileVieworEdit+'~'+$filesynced+'~'+$fileShareIntern+'~'+$fileShareExtern

            $usrVieworEdit='';$usrsynced='';$usrShareIntern='';$usrShareExtern='';
            foreach($actUsrCnts in $actUsrCntsArr){
                if($rptDate -eq $actUsrCnts.ReportDate){
                    if($actUsrCnts.ViewedOrEdited -ne ''){$usrVieworEdit=$actUsrCnts.ViewedOrEdited}else{$usrVieworEdit=0}
                    if($actUsrCnts.Synced -ne ''){$usrsynced=$actUsrCnts.Synced}else{$usrsynced=0}
                    if($actUsrCnts.SharedInternally -ne ''){$usrShareIntern=$actUsrCnts.SharedInternally}else{$usrShareIntern=0}
                    if($actUsrCnts.SharedExternally -ne ''){$usrShareExtern=$actUsrCnts.SharedExternally}else{$usrShareExtern=0}
                }
            }
            $usrRpt=$usrVieworEdit+'~'+$usrsynced+'~'+$usrShareIntern+'~'+$usrShareExtern

            $totOperUsrs=@()
            $actUsrDtlsArr | ForEach{if($_.LastActivityDate -eq $rptDate -and $_.IsDeleted -eq 'FALSE'){$totOperUsrs+=New-Object PSObject -Property @{'UsrDtls'=$_;'totalCnt'=([int]$_.ViewedOrEditedFileCount+[int]$_.SyncedFileCount+[int]$_.SharedInternallyFileCount+[int]$_.SharedExternallyFileCount)}}}
            $totOperUsrs | Sort-Object totalCnt -Descending | Select-Object -First 20 |foreach{$usrDtlsDD='FileInterationDD~'+$_.UsrDtls.LastActivityDate+'~!~'+$_.UsrDtls.UserPrincipalName+'~!~'+$_.totalCnt+'~!~'+$_.UsrDtls.ViewedOrEditedFileCount+'~!~'+$_.UsrDtls.SyncedFileCount+'~!~'+$_.UsrDtls.SharedInternallyFileCount+'~!~'+$_.UsrDtls.SharedExternallyFileCount+'~!~'+$_.UsrDtls.AssignedProducts;Write-Host $usrDtlsDD }

            $measures='Measures~'+$fileRpt+'~'+$usrRpt
            Write-Host $measures
        }
    }
}catch{
    $excepMsg=$_.Exception+($_.ScriptStackTrace)
    Write-Host 'Exception occurred -- '$excepMsg 
}

Remove-Item -Path $ODBFileCnts
Remove-Item -Path $ODBUsrCnts
Remove-Item -Path $ODBActUsr

