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

    $ConLyncVersnTotal=Eg-InvokeUrl -Url "https://graph.microsoft.com/v1.0/reports/getEmailAppUsageUserCounts(period='D7')"
}catch{
    $message= $_.Exception.Message + $_.ScriptStackTrace 
    Write-Error -Message "Error while running Eg-InvokeUrl function $message "
}

$enddate=Get-date
$diffence=(NEW-TIMESPAN –Start $readingdate –End (Get-Date) | Select-Object Days).Days
$strt=$enddate.AddDays(-($diffence+1))

$notFirsttime = $false
while($diffence -ge 1)
{
    if($notFirsttime){ $readingdate=$readingdate.AddDays(1) }
    $actualdate=$readingdate
    $notFirsttime = $true
    $ConLyncVersn =$ConLyncVersnTotal | Where-Object { [datetime]$_.ReportDate -eq $actualdate }       
    if($ConLyncVersn)
    {
        Write-Host 'ReadedDate for the Date#'$actualdate.tostring(“yyyy-MM-dd”)
        break
    }
    else
    {
        Write-Host 'thereIs No Data on#'$actualdate.tostring(“yyyy-MM-dd”)
    }
    $diffence=$diffence-1
}

if($ConLyncVersn)
{
    Write-Host 'ConLyncVersn_MailForMac  '  $ConLyncVersn.MailForMac
    Write-Host 'ConLyncVersn_OutlookForMac  '  $ConLyncVersn.OutlookForMac
    Write-Host 'ConLyncVersn_OutlookForWindows  '  $ConLyncVersn.OutlookForWindows
    Write-Host 'ConLyncVersn_OutlookForMobile  '  $ConLyncVersn.OutlookForMobile
    Write-Host 'ConLyncVersn_OtherForMobile  '  $ConLyncVersn.OtherForMobile
    Write-Host 'ConLyncVersn_OutlookForWeb  '  $ConLyncVersn.OutlookForWeb
    Write-Host 'ConLyncVersn_POP3App  '  $ConLyncVersn.POP3App
    Write-Host 'ConLyncVersn_IMAP4App  '  $ConLyncVersn.IMAP4App
    Write-Host 'ConLyncVersn_SMTPApp  '  $ConLyncVersn.SMTPApp
}
