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

clear

[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 -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]
$rptTopNDD=[int]$TestInputs[7]
$graphDetails=$TestInputs[8]
if($graphDetails -and $graphDetails -ne 'none'){
    $graphDetailsArr=($graphDetails).ToString() -Split ("~!~")
    $appId=$graphDetailsArr[0]
    $appSecret=$graphDetailsArr[1]
    $authString=$graphDetailsArr[2]
    $resource=$graphDetailsArr[3]
}
$langPath=$egurkhaPath+'\agent\config\O365_lang.ini'
$encTyp=Eg-GetINIContent -Path $langPath -Subject 'File_Type' -Key 'encoding'

if($proxyUser.toString().toLower().Trim() -eq 'none') { $proxyUser=$proxyUser.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim() }
if($proxyserver.toString().toLower().Trim().Contains('none')) { $proxyserver=$proxyserver.toString().toLower().Trim() }
if(!$proxyserver.Contains('none')){
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUser -ne 'none' -and $proxyPass -ne 'none'){
        $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUser, $(convertto-securestring $proxyPass -asplaintext -force)
        [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred   #[System.Net.CredentialCache]::DefaultNetworkCredentials
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
}

$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
}

$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 $appId, $appSecret
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"-ArgumentList $authString
        $context = $authContext.AcquireTokenAsync($resource, $creds).Result
        $authCode=$context.CreateAuthorizationHeader()
        $header = @{
            'Authorization'=$authCode
        }

        $query = [System.Text.Encoding]::$encTyp.GetString((Invoke-WebRequest -Method $Method -Headers $header -Uri $Url -UseBasicParsing).RawContentStream.ToArray())
        #$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 -Encoding $encTyp -Append -NoTypeInformation -Force
        }
    }
}
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$ODBFileCnts=$rptPath+'\ODBActFileCounts'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $ODBFileCnts
$ODBUsrCnts=$rptPath+'\ODBActUserCounts'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $ODBUsrCnts
$ODBActUsr=$rptPath+'\ODBActUsr'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $ODBActUsr

$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
    [System.GC]::GetTotalMemory($true) | out-null
    $actFileCntsArr=Import-Csv $ODBFileCnts -Encoding $encTyp
    $actUsrCntsArr=Import-Csv $ODBUsrCnts -Encoding $encTyp
    $actUsrDtlsArr=Import-Csv $ODBActUsr -Encoding $encTyp


    $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 $rptTopNDD |foreach{ $asigndPrdts=([String]$_.UsrDtls.AssignedProducts).Trim();if($asigndPrdts.Length -gt 1999){$asigndPrdts=$asigndPrdts.Substring(0,1995)+'...'};$usrDtlsDD='FileInterationDD~'+$_.UsrDtls.LastActivityDate+'~!~'+$_.UsrDtls.UserPrincipalName+'~!~'+$_.totalCnt+'~!~'+$_.UsrDtls.ViewedOrEditedFileCount+'~!~'+$_.UsrDtls.SyncedFileCount+'~!~'+$_.UsrDtls.SharedInternallyFileCount+'~!~'+$_.UsrDtls.SharedExternallyFileCount+'~!~'+$asigndPrdts;Write-Host $usrDtlsDD}

            $measures='Measures~'+$fileRpt+'~'+$usrRpt
            Write-Host $measures
        }
    }
}catch{
    $excepMsg=($_.Exception.Message)+($_.ScriptStackTrace) 
    Write-Host "Exception occurred -- $excepMsg "
}
if([System.IO.File]::Exists($ODBFileCnts) -eq 'True'){
    Remove-Item -Path $ODBFileCnts
}
if([System.IO.File]::Exists($ODBUsrCnts) -eq 'True'){
    Remove-Item -Path $ODBUsrCnts
}
if([System.IO.File]::Exists($ODBActUsr) -eq 'True'){
    Remove-Item -Path $ODBActUsr
}
[System.GC]::GetTotalMemory($true) | out-null
