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()

$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
        }
        $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=@()
        $jsonRpt='{ "Usage" :['+$reprts+']}'
        $obj=ConvertFrom-Json -InputObject $jsonRpt
        return $obj.Usage 
    }
}

$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$deviceusagecsv = $rptPath+'\TeamsDeviceUsageUsers'+$timenow+'.csv'
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 "
}
$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

$devicusgeurl ="https://graph.microsoft.com/v1.0/reports/getTeamsDeviceUsageUserCounts(period='D7')"

try{

     $TeamsDevUsgtotal=Eg-InvokeUrl -Url $devicusgeurl

}catch{
    $exp=$_.Exception.Message + $_.ScriptStackTrace
    Write-Error -Message "Exception while running the deviceusage report" $exp
}



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

$notFirsttime = $false
while($diffence -ge 1)
{
    if($notFirsttime){ $readingdate=$readingdate.AddDays(1) }
    $actualdate=$readingdate
    $notFirsttime = $true
    $TeamsDevUsg =$TeamsDevUsgtotal | Where-Object { [datetime]$_.ReportDate -eq $actualdate }       
    if($TeamsDevUsg)
    {
        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
}


   foreach($dev in $TeamsDevUsg){
        $isFlag=$false
        $dev.PSObject.Properties | ForEach-Object{
            if($_.Name -eq 'ReportDate'){break}
            
            if($isFlag){
                $write='#deviceinfo'+$_.Name+' ~ '+$_.Value
                Write-Host $write  
            }

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

