<#
    /*****************************************************************************
    Author            :       Mounika Kuna
    Purpose           :       Provides User Yammer Activity Details
    Created           :       18/07/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]
$readingdate=[datetime]$TestInputs[3]
$rptNam=$TestInputs[4]
$graphDtls=$TestInputs[5]
#>

$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\YMR\'+$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

$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$YammerusrActivityCSV=$rptPath+'\YammerUserActivity'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $YammerusrActivityCSV
[System.GC]::GetTotalMemory($true) | out-null
Eg-InvokeGraphUrl -Url "https://graph.microsoft.com/v1.0/reports/getyammeractivityuserdetail(period='D7')" -filePath $YammerusrActivityCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource

$TotalYammerActivities=Import-Csv $YammerusrActivityCSV -Encoding $encTyp

$diffence=(NEW-TIMESPAN –Start $readingdate –End (Get-Date) | Select-Object Days).Days
[System.GC]::GetTotalMemory($true) | out-null
$notFirsttime = $false
while($diffence -ge 1)
{
    if($notFirsttime){ $readingdate=$readingdate.AddDays(1) }
    $actualdate=$readingdate
    $notFirsttime = $true
    $TotalYammerActiv =$TotalYammerActivities | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
    if($TotalYammerActiv)
    {
        Write-Host 'ReadDate for the Date#'$actualdate.tostring(“yyyy-MM-dd”)
        break
    }
    else
    {
        Write-Host 'thereIs No Data on#'$actualdate.tostring(“yyyy-MM-dd”)
    }
    $diffence=$diffence-1
}
[System.GC]::GetTotalMemory($true) | out-null
try{
	$TotalYammerActiv = $TotalYammerActiv | Where-Object { $_.UserPrincipalName -ne '(Unknown)' } 
    foreach($User in $TotalYammerActiv){
        $hasLicenses=0
        $assignedProducts=$User.AssignedProducts
        if($assignedProducts -and $assignedProducts.Trim().Length -gt 0){
            $hasLicenses=1
        }
        $UserPrincipalName=$User.UserPrincipalName
        $PostedCount=$User.PostedCount
        $ReadCount=$User.ReadCount
        $LikedCount=$User.LikedCount        
        $Output = 'info&Measures='+$UserPrincipalName+'~'+$PostedCount+'~'+$ReadCount+'~'+$LikedCount+'~'+$hasLicenses
        Write-Host $Output        
    }
}catch{    
    $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	Write-error "Error Occured in YMRUserActvtyTest Script >>> "$exceptionmsg 
}
[System.GC]::GetTotalMemory($true) | out-null
if([System.IO.File]::Exists($YammerusrActivityCSV) -eq 'True'){
    Remove-Item $YammerusrActivityCSV
}
