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]
$DateProxyhostRepName=($TestInputs[4]).ToString().Split("#")
$readingDateUserdetails=[datetime]($DateProxyhostRepName[0].Trim())
$readingDateUserCounts=[datetime]($DateProxyhostRepName[1].Trim())
$proxyserverip=($DateProxyhostRepName[2]).ToString().trim()
$reportingname=($DateProxyhostRepName[3]).ToString().trim()

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


$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 -Append -NoTypeInformation -Force
        } 
    }
}




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
            }
        }
    }

$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'

$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
            $TeamsUsg= import-csv $usrActUsrDt | where-object { $_.LastActivityDate } | 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 "error while getting the user activities details on $actualdate  $message " 
            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 "
}


$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)
{
    Write-Host 'top10chatmsgusrs#' $chatusrs.UserPrincipalName ~!~ $chatusrs.LastActivityDate ~!~ $chatusrs.TeamChatMessageCount ~!~ $chatusrs.PrivateChatMessageCount ~!~ $chatusrs.CallCount ~!~ $chatusrs.MeetingCount ~!~ $chatusrs.HasOtherAction ~!~ $chatusrs.IsDeleted ~!~ $chatusrs.DeletedDate ~!~ $chatusrs.AssignedProducts
}
$top10chatmsgUsrs=$null

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

foreach($chatusrs in $top10PrivtechatmsgUsrs)
{
    Write-Host 'top10privatechatusrs#' $chatusrs.UserPrincipalName ~!~ $chatusrs.LastActivityDate ~!~ $chatusrs.TeamChatMessageCount ~!~ $chatusrs.PrivateChatMessageCount ~!~ $chatusrs.CallCount ~!~ $chatusrs.MeetingCount ~!~ $chatusrs.HasOtherAction ~!~ $chatusrs.IsDeleted ~!~ $chatusrs.DeletedDate ~!~ $chatusrs.AssignedProducts
}
$top10PrivtechatmsgUsrs=$null

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

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

foreach($chatusrs in $top10MeetingscntUsrs)
{
    Write-Host 'top10meetingsusrs#' $chatusrs.UserPrincipalName ~!~ $chatusrs.LastActivityDate ~!~ $chatusrs.TeamChatMessageCount ~!~ $chatusrs.PrivateChatMessageCount ~!~ $chatusrs.CallCount ~!~ $chatusrs.MeetingCount ~!~ $chatusrs.HasOtherAction ~!~ $chatusrs.IsDeleted ~!~ $chatusrs.DeletedDate ~!~ $chatusrs.AssignedProducts
}
$top10MeetingscntUsrs=$null
$TeamsUsg=$null


$usrActUsrcunts = $rptPath+'\MTMUsrActUserCounts'+$timenow+'.csv'
$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{
    $totalTeamsActSumry= import-csv $usrActUsrcunts | 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'
