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]
#>

$domain=Eg-GetDomain -userName $username -Password $password -proxyUsr $proxyUser -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver
$rptPath=$egurkhaPath+'\agent\ODB\'+$rptNam
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

$toReadDat=$readDat.tostring(“yyyy-MM-dd”)
$azureVal=Eg-GetAzureEnv -UserName $username -subject 'O365_Graph'
$azureEnvArr=$azureVal.Split(',')
$clientArr=Get-GraphClientSecret -InitialDomain $domain
if($clientArr -ne $null){
    $clientId=$clientArr[0].ToString().Trim()
    $clientSecret=$clientArr[1].ToString().Trim()
}
$authStr=$azureEnvArr[0].ToString().Trim()+$domain
$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))
$ODBUsageAccDtls=$rptPath+'\ODBFileUsageAccDtls'+$timenow+'.csv'
$url1="https://graph.microsoft.com/v1.0/reports/getOneDriveUsageAccountDetail(period='D7')"
Try{
     Eg-InvokeUrl -Url $url1 -Method 'Get' -PropsVal 'ReportDate' -filePath $ODBUsageAccDtls
     $usagAccDtlArr=Import-Csv $ODBUsageAccDtls

     $accDtlsRptDat=$usagAccDtlArr | select ReportRefreshDate -First 1
     $accDtlsRptDat=($accDtlsRptDat.ReportRefreshDate)

     if([datetime]$accDtlsRptDat -ge [datetime]$toReadDat){
        Write-Host 'ReadedDate for the Date#'$accDtlsRptDat
        
        $totalFiles=0
        $sortUsagAccDtl=@()
        $usagAccDtlArr | foreach{if($_.FileCount -ne '' -and $_.IsDeleted -eq 'FALSE'){if($inActivSites){}   $totalFiles=$totalFiles+$_.FileCount}; $sortUsagAccDtl+=$_}
        $sortUsagAccDtl|Sort-Object {$_.FileCount -as [Int]} -Descending | Select-Object -First 20 |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};$totFilesDD='TotalFilesDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount;Write-Host $totFilesDD}
        
        $activFiles=0
        $usagAccDtlArr | foreach{if($_.ActiveFileCount -ne '' -and $_.IsDeleted -eq 'FALSE'){$activFiles=$activFiles+$_.ActiveFileCount}}
        $sortUsagAccDtl | Sort-Object {$_.ActiveFileCount -as [Int]} -Descending | Select-Object -First 20 |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};$actFilesDD='ActivFilesDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount;Write-Host $actFilesDD}

        $acivFilesPercent=[math]::Round((([int]$activFiles/[int]$totalFiles)*100),2)

        $measure='measures~'+[String]$totalFiles+'~'+[String]$activFiles+'~'+$acivFilesPercent
        Write-Host $measure
    }
}
Catch{
    $excepMsg=$_.Exception+($_.ScriptStackTrace)
    Write-Host 'Exception occurred -- '$excepMsg
}

Remove-Item -Path $ODBUsageAccDtls

