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

$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”)

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
    {
        $typePath=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
        Add-Type -Path $typePath
        $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))
$ODBUsageAccDtls=$rptPath+'\ODBFileUsageAccDtls'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $ODBUsageAccDtls
$url1="https://graph.microsoft.com/v1.0/reports/getOneDriveUsageAccountDetail(period='D7')"
Try{
     Eg-InvokeUrl -Url $url1 -Method 'Get' -PropsVal 'ReportDate' -filePath $ODBUsageAccDtls
     [System.GC]::GetTotalMemory($true) | out-null
     $usagAccDtlArr=Import-Csv $ODBUsageAccDtls -Encoding $encTyp

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

if([System.IO.File]::Exists($ODBUsageAccDtls) -eq 'True'){
    Remove-Item -Path $ODBUsageAccDtls
}
[System.GC]::GetTotalMemory($true) | out-null
