clear
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value
$egurkhaPath=$egInstallpath.Value.ToString()
$egEncryPath=$egurkhaPath+"\lib\EGFileEncryption.psm1"
$egDatnKy=$egurkhaPath+'\lib\GetDatnKeyFiles.psm1'
Import-Module $egEncryPath,$egDatnKy

$TestInputs=$args
$userName=$TestInputs[0]
$Password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyUsr=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$DateProxyhostRepName=($TestInputs[4]).ToString().Split("#")
$readeddate=[datetime]($DateProxyhostRepName[0].Trim())
$proxyserverip=($DateProxyhostRepName[1]).ToString().trim()
$reportingname=($DateProxyhostRepName[2]).ToString().trim()


$ToReadDate=$readeddate.tostring(“yyyy-MM-dd”)
$proxyserver='http://'+$proxyserverip
$domain=Eg-GetDomain -userName $userName -Password $Password -proxyUsr $proxyUsr -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver



$rptPath=$egurkhaPath+'\agent\O365\'+$reportingname
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

try{
    $msGraphPath=$egurkhaPath+"\agent\O365\MsGraph"
    $keyFileNam = '\GraphDetailsKey.dat'
    $unProtPath= $msGraphPath+'\GraphDetails.dat'
    $kvalue= Get-Content -Path $msGraphPath$keyFileNam
    $null=Unprotect-File $unProtPath -Algorithm AES -KeyAsPlainText $kvalue -DstSuffix '.txt'
    $SkypeInput=$msGraphPath+"\GraphDetails.txt"
    $GetInput = Get-Content -Path $SkypeInput
}catch{
    Write-Error -Message "File not found. The $GetInput location does not contain GraphDetails "
}



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

    Process
    {
        $query = Invoke-RestMethod -Method 'Get' -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
        return $reports.Usage
    }
}


$flag=$false
foreach($inp in $GetInput){
    if($inp.StartsWith('[') -and $inp.Contains($domain)){
        $flag=$true
    }
    if($flag){
        if($inp.Contains("client_id")){
            $appId =$inp.ToString().Substring($inp.IndexOf('~')+1)
        }
        if($inp.Contains("client_secret")){
            $appSecret =$inp.ToString().Substring($inp.IndexOf('~')+1)
        }
        if($inp.Contains("TenantName")){
            $tenantID=$inp.ToString().Substring($inp.IndexOf('~')+1)
        }
        if($inp.Contains("Authority")){
            $authString = $inp.ToString().Substring($inp.IndexOf('~')+1)
            $authString=$authString+$domain
        }
        if($inp.Contains("Resource")){
            $Resource =$inp.ToString().Substring($inp.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

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



$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$SrvUsrCntcsv = $rptPath+'\ServicesUserCounts'+$timenow+'.csv'
$O365Servicesurl= "https://graph.microsoft.com/v1.0/reports/getOffice365ServicesUserCounts(period='D7')"
try{
   $SrvUsrCntlist=Eg-InvokeUrl -Url $O365Servicesurl -filePath $SrvUsrCntcsv -header $header

}catch{
    $_.Exception
    Write-Error -Message "File not found. The $reportingname location does not contain deviceusage report"
}

$reportdate=$SrvUsrCntlist | select ReportRefreshDate -First 1
   foreach($service in $SrvUsrCntlist){
        $reportdate=($service.ReportRefreshDate)
        if([datetime]$reportdate -ge [datetime]$ToReadDate)
        {
            Write-Host 'ReadedDate for the Date#'$reportdate
        } 
        else{ 
         Write-Host 'thereIs No Data on#'$ToReadDate
         exit  
         }
        $isFlag=$false
        $service.PSObject.Properties | ForEach-Object{
            if($_.Name -eq 'ReportPeriod'){break}
            
            if($isFlag){
                $write='services#'+$_.Name+' ~ '+$_.Value
                Write-Host $write  
            }

            if($_.Name -eq 'ReportRefreshDate'){$isFlag=$true}
        }
  }
