<#
    /*****************************************************************************
    Author            :       Mounika Kuna
    Purpose           :       Provides Teams Users Details
    Created           :       15/09/2020    
    /*****************************************************************************
#>

$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
$proxyUser=$TestInputs[0]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyserver=$TestInputs[2]
$toreadDate_UsersActvty=[datetime]$TestInputs[3]
$toreadDate_UsersDevUsage=[datetime]$TestInputs[4]
$rptNam=$TestInputs[5]
$graphDtls=$TestInputs[6]
#>

$graphDtlsArr=$graphDtls.ToString() -split '~!~'
$appId=$graphDtlsArr[0]
$appSecret=$graphDtlsArr[1]
$authString=$graphDtlsArr[2]
$resource=$graphDtlsArr[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.ToString().ToLower().Contains('none')){
    #$proxyserverip='http://'+$proxyserver
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUser.ToString().ToLower() -ne 'none' -and $proxyPass.ToString().ToLower() -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\MTM\'+$rptNam
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

$typePath=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
Add-Type -Path $typePath

[System.GC]::GetTotalMemory($true) | out-null
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$TeamsUsrActvtyDtlCSV=$rptPath+'\TeamsUsrActvtyDtl'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $TeamsUsrActvtyDtlCSV

$url1 = "https://graph.microsoft.com/v1.0/reports/getTeamsUserActivityUserDetail(period='D7')"
while($true){
    Eg-InvokeGraphUrl -Url $url1 -filePath $TeamsUsrActvtyDtlCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource
    $TeamsUsrActvtytotal=Import-Csv $TeamsUsrActvtyDtlCSV -Encoding $encTyp
    $url1=$TeamsUsrActvtytotal.'@odata.nextLink'
    if($url1 -eq $null -or $url1 -eq ''){
        break
    }
}
$firstRecord1=$TeamsUsrActvtytotal | select ReportRefreshDate -First 1
$ReportRefreshDate1=($firstRecord1.ReportRefreshDate)
$diffence1=(NEW-TIMESPAN –Start $toreadDate_UsersActvty –End $ReportRefreshDate1 | Select-Object Days).Days
if($diffence1 -ge 1){$reportRefreshed1=$true}

[System.GC]::GetTotalMemory($true) | out-null
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$DeviceUsgByUsrCSV=$rptPath+'\DeviceUsgByUsr'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $DeviceUsgByUsrCSV

$url2="https://graph.microsoft.com/v1.0/reports/getTeamsDeviceUsageUserDetail(period='D7')"
while($true){
    Eg-InvokeGraphUrl -Url $url2 -filePath $DeviceUsgByUsrCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource
    $TotalDeviceUsgByUsr=Import-Csv $DeviceUsgByUsrCSV -Encoding $encTyp
    $url2=$TotalDeviceUsgByUsr.'@odata.nextLink'
    if($url2 -eq $null -or $url2 -eq ''){
        break
    }
}
$firstRecord2=$TotalDeviceUsgByUsr | select ReportRefreshDate -First 1
$ReportRefreshDate2=($firstRecord2.ReportRefreshDate)
$diffence2=(NEW-TIMESPAN –Start $toreadDate_UsersDevUsage –End $ReportRefreshDate2 | Select-Object Days).Days
if($diffence2 -ge 1){$reportRefreshed2=$true}

[System.GC]::GetTotalMemory($true) | out-null
if($reportRefreshed1 -and $reportRefreshed2){
    $diffence=(NEW-TIMESPAN –Start $toreadDate_UsersActvty –End (Get-Date) | Select-Object Days).Days
    $notFirsttime = $false
    while($diffence -ge 1)
    {
        if($notFirsttime){ $toreadDate_UsersActvty=$toreadDate_UsersActvty.AddDays(1) }
        $actualdate=$toreadDate_UsersActvty
        $notFirsttime = $true
        $TeamsUsrActivity =$TeamsUsrActvtytotal | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
        if($TeamsUsrActivity)
        {
            Write-Host 'ReadDate of UsersActvty Data on#'$actualdate.tostring(“yyyy-MM-dd”);
            break
        }
        else
        {
            Write-Host 'thereIs No UsersActvty Data on#'$actualdate.tostring(“yyyy-MM-dd”)
        }
        $diffence=$diffence-1
    }
	[System.GC]::GetTotalMemory($true) | out-null
	
    $diffence=(NEW-TIMESPAN –Start $toreadDate_UsersDevUsage –End (Get-Date) | Select-Object Days).Days
    $notFirsttime = $false
    while($diffence -ge 1)
    {
        if($notFirsttime){ $toreadDate_UsersDevUsage=$toreadDate_UsersDevUsage.AddDays(1) }
        $actualdate=$toreadDate_UsersDevUsage
        $notFirsttime = $true
        $TotalDeviceUsg =$TotalDeviceUsgByUsr | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
        if($TotalDeviceUsg)
        {
            Write-Host 'ReadDate of UsersDevUsage Data on#'$actualdate.tostring(“yyyy-MM-dd”)
            break
        }
        else
        {
            Write-Host 'thereIs No UsersDevUsage Data on#'$actualdate.tostring(“yyyy-MM-dd”)
        }
        $diffence=$diffence-1
    }
	[System.GC]::GetTotalMemory($true) | out-null
}
$TeamsUsrActivity = $TeamsUsrActivity | Where-Object { $_.UserPrincipalName -ne '(Unknown)' } 
foreach($usr in $TeamsUsrActivity) {
    $flag = 0;
    if($usr.HasOtherAction -eq 'Yes') {
        $flag = 1;
    }
    $hasLicenses=0
    $assignedProducts=$usr.AssignedProducts
    if($assignedProducts -and $assignedProducts.Trim().Length -gt 0){
        $hasLicenses=1
    }
    $Output='ActivityDetails~'+$usr.UserPrincipalName+'~'+$usr.TeamChatMessageCount+'~'+$usr.PrivateChatMessageCount+'~'+$usr.CallCount+'~'+$usr.MeetingCount+'~'+$flag+'~'+$hasLicenses
    Write-Host $Output
}
[System.GC]::GetTotalMemory($true) | out-null
if([System.IO.File]::Exists($TeamsUsrActvtyDtlCSV) -eq 'True'){
    Remove-Item $TeamsUsrActvtyDtlCSV
}

$TotalDeviceUsg = $TotalDeviceUsg | Where-Object { $_.UserPrincipalName -ne '(Unknown)' } 
foreach($dev in $TotalDeviceUsg) {
    $Web = 0;
    $winPh = 0;
    $ios = 0;
    $mac = 0;
    $androidPh = 0;
    $windows = 0;

    if($dev.UsedWeb -eq 'Yes') {
        $Web = 1;
    }
    
    if($dev.UsedWindowsPhone -eq 'Yes') {
        $winPh = 1;
    }
    
    if($dev.UsediOS -eq 'Yes') {
        $ios = 1;
    }
    
    if($dev.UsedMac -eq 'Yes') {
        $mac = 1;
    }
    
    if($dev.UsedAndroidPhone -eq 'Yes') {
        $androidPh = 1;
    }
    
    if($dev.UsedWindows -eq 'Yes') {
        $windows = 1;
    }    
    $Output='UsageDetails~'+$dev.UserPrincipalName+'~'+$web+'~'+$winPh+'~'+$ios+'~'+$mac+'~'+$androidPh+'~'+$windows
    Write-Host $Output
}
[System.GC]::GetTotalMemory($true) | out-null
if([System.IO.File]::Exists($DeviceUsgByUsrCSV) -eq 'True'){
    Remove-Item $DeviceUsgByUsrCSV
}
