$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=$egurkhaPath+"\lib\EGFileEncryption.psm1"
$egDatnKy=$egurkhaPath+'\lib\GetDatnKeyFiles.psm1'
Import-Module $egEncryPath,$egDatnKy

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

$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($proxyUsr.toString().toLower().Trim() -eq 'none') { $proxyUsr=$proxyUsr.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim() }
if($proxyserverip.toString().toLower().Trim().Contains('none')) { $proxyserverip=$proxyserverip.toString().toLower().Trim() }
if(!$proxyserverip.ToString().ToLower().Contains('none')){
    $proxyserver='http://'+$proxyserverip
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUsr.ToString().ToLower() -ne 'none' -and $proxyPass.ToString().ToLower() -ne 'none'){
        $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
        [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred   #[System.Net.CredentialCache]::DefaultNetworkCredentials
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
}

$teamChatMsgs=0
$prvtChatMsgs=0
$calls=0
$meetings=0
$otheract=0
$rptPath=$egurkhaPath+'\agent\MTM\'+$reportingname
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

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

    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=@()
        $jsonreprt='{ "Usage" :['+$reprts+']}'
        $reports=$jsonreprt | ConvertFrom-Json

        for($i=0;$i -lt $reports.Usage.Length ;$i++ ){   
            $reports.Usage[$i] |Export-Csv $filePath -Encoding $encTyp -Append -NoTypeInformation -Force
        } 
    }
}

$path=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
Add-Type -Path $path
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$usrActUsrDt = $rptPath+'\MTMUsrActUsrDetils'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $usrActUsrDt

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

try{
    $notFirsttime = $false
    while($diffence -gt 1)
    {
        if($notFirsttime){ $readingDateUserdetails=$readingDateUserdetails.AddDays(1) }
        $actualdate=$readingDateUserdetails.tostring(“yyyy-MM-dd”)
        $actualdate
        $notFirsttime = $true
        try{
            $UserActivitiesUrl ="https://graph.microsoft.com/v1.0/reports/getTeamsUserActivityUserDetail(date=$actualdate)"    #(period='D7')"
            Eg-InvokeUrl -Url $UserActivitiesUrl -filePath $usrActUsrDt
            if([System.IO.File]::Exists($usrActUsrDt) -eq 'True'){
                $TeamsUsg= import-csv $usrActUsrDt -Encoding $encTyp | where-object { $_.LastActivityDate -and $_.UserPrincipalName -notlike '*unknown*'} | Select-Object *  #| Sort-Object { $_.ReportDate -as [datetime] } -Descending | select -First 1    
            }
            Write-Host 'ReadedDate of user actvities Date#'$actualdate
            break

        }catch{
            $message= $_.Exception.Message + $_.ScriptStackTrace 
            Write-Error -Message "getTeamsUserActivityUserDetail - Report not yet generated for this $actualdate yet."
            Write-Host 'thereIs No user actvities on Data#'$actualdate
        }  

        $diffence=$diffence-1
    }

}catch{
    $message= $_.Exception.Message + $_.ScriptStackTrace 
    Write-Error -Message "File not found. The $reportingname location does not contain UserActivity report $message "
}
[System.GC]::GetTotalMemory($true) | out-null

$UnqUsrtotalchatmsgcnt=($TeamsUsg | Measure-Object "TeamChatMessageCount" -Sum | select Sum).Sum
if(!$UnqUsrtotalchatmsgcnt){$UnqUsrtotalchatmsgcnt=0}
$UnqUsrtotalPrivtechatmsgcnt=($TeamsUsg | Measure-Object "PrivateChatMessageCount" -Sum | select Sum).Sum
$UnqUsrtotalCallcnt=($TeamsUsg | Measure-Object "CallCount" -Sum | select Sum).Sum
$UnqUsrtotalMeetingscnt=($TeamsUsg | Measure-Object "MeetingCount" -Sum | select Sum).Sum
$UnqUsrtotlotherActUsrs=($TeamsUsg | where-object { $_.HasOtherAction -eq 'Yes' }).count


$top10chatmsgUsrs=$TeamsUsg | Where-Object { $_.TeamChatMessageCount -gt 0 } |Sort-Object  { $_.TeamChatMessageCount -as [int] } -Descending | select -First 10
foreach($chatusrs in $top10chatmsgUsrs)
{
    $asigndPrdts=([String]$chatusrs.AssignedProducts).Trim()
    if($asigndPrdts.Length -gt 1999){
        $asigndPrdts=$asigndPrdts.Substring(0,1995)+'...'
    }
    Write-Host 'top10chatmsgusrs#' $chatusrs.UserPrincipalName ~!~ $chatusrs.LastActivityDate ~!~ $chatusrs.TeamChatMessageCount ~!~ $chatusrs.PrivateChatMessageCount ~!~ $chatusrs.CallCount ~!~ $chatusrs.MeetingCount ~!~ $chatusrs.HasOtherAction ~!~ $chatusrs.IsDeleted ~!~ $chatusrs.DeletedDate ~!~ $asigndPrdts
}
$top10chatmsgUsrs=$null

$top10PrivtechatmsgUsrs=$TeamsUsg | Where-Object { $_.PrivateChatMessageCount -gt 0 } | Sort-Object  { $_.PrivateChatMessageCount -as [int] } -Descending | select -First 10

foreach($chatusrs in $top10PrivtechatmsgUsrs)
{
    $asigndPrdts=([String]$chatusrs.AssignedProducts).Trim()
    if($asigndPrdts.Length -gt 1999){
        $asigndPrdts=$asigndPrdts.Substring(0,1995)+'...'
    }
    Write-Host 'top10privatechatusrs#' $chatusrs.UserPrincipalName ~!~ $chatusrs.LastActivityDate ~!~ $chatusrs.TeamChatMessageCount ~!~ $chatusrs.PrivateChatMessageCount ~!~ $chatusrs.CallCount ~!~ $chatusrs.MeetingCount ~!~ $chatusrs.HasOtherAction ~!~ $chatusrs.IsDeleted ~!~ $chatusrs.DeletedDate ~!~ $asigndPrdts
}
$top10PrivtechatmsgUsrs=$null

$top10CallcntUsrs=$TeamsUsg | Where-Object { $_.CallCount -gt 0 }  | Sort-Object  { $_.CallCount -as [int] } -Descending | select -First 10
foreach($chatusrs in $top10CallcntUsrs)
{
    $asigndPrdts=([String]$chatusrs.AssignedProducts).Trim()
    if($asigndPrdts.Length -gt 1999){
        $asigndPrdts=$asigndPrdts.Substring(0,1995)+'...'
    }
    Write-Host 'top10callcntusrs#' $chatusrs.UserPrincipalName ~!~ $chatusrs.LastActivityDate ~!~ $chatusrs.TeamChatMessageCount ~!~ $chatusrs.PrivateChatMessageCount ~!~ $chatusrs.CallCount ~!~ $chatusrs.MeetingCount ~!~ $chatusrs.HasOtherAction ~!~ $chatusrs.IsDeleted ~!~ $chatusrs.DeletedDate ~!~ $asigndPrdts
}
$top10CallcntUsrs=$null

$top10MeetingscntUsrs=$TeamsUsg | Where-Object { $_.MeetingCount -gt 0 }  | Sort-Object  { $_.MeetingCount -as [int] } -Descending | select -First 10

foreach($chatusrs in $top10MeetingscntUsrs)
{
    $asigndPrdts=([String]$chatusrs.AssignedProducts).Trim()
    if($asigndPrdts.Length -gt 1999){
        $asigndPrdts=$asigndPrdts.Substring(0,1995)+'...'
    }
    Write-Host 'top10meetingsusrs#' $chatusrs.UserPrincipalName ~!~ $chatusrs.LastActivityDate ~!~ $chatusrs.TeamChatMessageCount ~!~ $chatusrs.PrivateChatMessageCount ~!~ $chatusrs.CallCount ~!~ $chatusrs.MeetingCount ~!~ $chatusrs.HasOtherAction ~!~ $chatusrs.IsDeleted ~!~ $chatusrs.DeletedDate ~!~ $asigndPrdts
}
$top10MeetingscntUsrs=$null
$TeamsUsg=$null


$usrActUsrcunts = $rptPath+'\MTMUsrActUserCounts'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $usrActUsrcunts
$UserActiUsrCntsUrl ="https://graph.microsoft.com/v1.0/reports/getTeamsUserActivityUserCounts(period='D7')"  
Eg-InvokeUrl -Url $UserActiUsrCntsUrl -filePath $usrActUsrcunts
$diffence1=(NEW-TIMESPAN –Start $readingDateUserCounts –End (Get-Date) | Select-Object Days).Days


try{
    if([System.IO.File]::Exists($usrActUsrcunts) -eq 'True'){
        $totalTeamsActSumry= import-csv $usrActUsrcunts -Encoding $encTyp | Select-Object *  | Sort-Object { $_.ReportDate -as [datetime] } # -Descending | select -First 1
    }

    $notFirsttime = $false
    while($diffence1 -gt 1)
    {
        if($notFirsttime){ $readingDateUserCounts=$readingDateUserCounts.AddDays(1) }
        $actualdate=$readingDateUserCounts.tostring(“yyyy-MM-dd”)
        $notFirsttime = $true
        $TeamsActSumry =$totalTeamsActSumry | Where-Object { ($_.ReportDate) -eq $actualdate }
        if($TeamsActSumry)
        {
            Write-Host 'ReadedDate of usercounts Date#'$actualdate
            break
        }

        else
        {
            Write-Host 'thereIs No usercounts on Data#'$actualdate
        }
        $diffence1=$diffence1-1
    }

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


if($TeamsActSumry){

    $teamChatMsgs=$TeamsActSumry.TeamChatMessages
    $prvtChatMsgs=$TeamsActSumry.PrivateChatMessages
    $calls=$TeamsActSumry.Calls
    $meetings=$TeamsActSumry.Meetings
    $otheract=$TeamsActSumry.OtherActions
}

if($TeamsActSumry -or $TeamsUsg){ 
Write-Host '#measures' $teamChatMsgs ~ $prvtChatMsgs ~ $calls ~ $meetings ~ $otheract ~ $UnqUsrtotalchatmsgcnt ~ $UnqUsrtotalPrivtechatmsgcnt ~ $UnqUsrtotalCallcnt ~ $UnqUsrtotalMeetingscnt ~ $UnqUsrtotlotherActUsrs
}
$csvDir=$rptPath+'/'
Eg-DeleteCsvFiles -FilePath $csvDir -Pattern 'MTMUsrActUsrDetils'
Eg-DeleteCsvFiles -FilePath $csvDir -Pattern 'MTMUsrActUserCounts'
[System.GC]::GetTotalMemory($true) | out-null