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]
$DateProxyhost=($TestInputs[4]).ToString().Split("#")
$readingdate=[datetime]($DateProxyhost[0].Trim())
$proxyserverip=($DateProxyhost[1]).ToString().trim()

$appId=''
$appSecret=''
$tenantID=''
$authString=''

$proxyserver='http://'+$proxyserverip
$domain=Eg-GetDomain -userName $userName -Password $Password -proxyUsr $proxyUsr -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver


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

    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
        }
        $queryRes = Invoke-RestMethod -Method 'Get' -Headers $header -Uri $Url 
        $queryRes=$queryRes.Replace('ï»¿','')
	$queryRes=$queryRes.Replace('(Byte)','')
        $queryRes=$queryRes.Replace(' ','')

        $resultarray = ConvertFrom-Csv -InputObject $queryRes
        $reprts=$resultarray | ConvertTo-Json 
        $jsonRpt=@()
        $jsonRpt='{ "Usage" :['+$reprts+']}'
        $obj=ConvertFrom-Json -InputObject $jsonRpt
        return $obj.Usage
    }
}



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 " $_.Exception.Message  $_.ScriptStackTrace
}

$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
            }
        }
    }
try{
    $path=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
    Add-Type -Path $path
    $UsrLyncVersn=Eg-InvokeUrl -Url "https://graph.microsoft.com/v1.0/reports/getEmailAppUsageVersionsUserCounts(period='D7')"

}catch{
    $message= $_.Exception.Message + $_.ScriptStackTrace 
    Write-Error -Message "Error while running Eg-InvokeUrl function $message "
}


if($UsrLyncVersn -and [datetime]$UsrLyncVersn.ReportRefreshDate -ge $readingdate)
{
    Write-Host 'UsrLyncVersn_Outlook2016  '  $UsrLyncVersn.Outlook2016
    Write-Host 'UsrLyncVersn_Outlook2013  '  $UsrLyncVersn.Outlook2013
    Write-Host 'UsrLyncVersn_Outlook2010  '  $UsrLyncVersn.Outlook2010
    Write-Host 'UsrLyncVersn_Outlook2007  '  $UsrLyncVersn.Outlook2007
    Write-Host 'UsrLyncVersn_Undetermined  '  $UsrLyncVersn.Undetermined
    Write-Host 'ReadedDate for the Date#'$UsrLyncVersn.ReportRefreshDate
}
else{ Write-Host 'thereIs No Data on#' $readingdate.tostring(“yyyy-MM-dd”) }