<#
    /*****************************************************************************
    Author            :       Mounika Kuna
    Purpose           :       Provides Yammer Users By Activity Details
    Created           :       26/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))
$YammerUnqUsrActivityCSV=$rptPath+'\YammerUnqUsrActivity'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $YammerUnqUsrActivityCSV
[System.GC]::GetTotalMemory($true) | out-null
Eg-InvokeGraphUrl -Url "https://graph.microsoft.com/v1.0/reports/getYammerActivityUserCounts(period='D7')" -filePath $YammerUnqUsrActivityCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource

$TotalYammerUnqUsrActivity=Import-Csv $YammerUnqUsrActivityCSV -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
    $UnqUsrActivity =$TotalYammerUnqUsrActivity | Where-Object { [datetime]$_.ReportDate -eq $actualdate }       
    if($UnqUsrActivity)
    {
        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{
    if($UnqUsrActivity.Liked -eq ""){ $Liked = 0 }else{ $Liked = $UnqUsrActivity.Liked }
    if($UnqUsrActivity.Posted -eq ""){ $Posted = 0 }else{ $Posted = $UnqUsrActivity.Posted }
    if($UnqUsrActivity.Read -eq ""){ $Read = 0 }else{ $Read = $UnqUsrActivity.Read }

    $Metrics='Metrics='+$Liked+'~'+$Posted+'~'+$Read
    Write-Host $Metrics
}catch{    
    $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	Write-error "Error Occured in Yammer Users by Activity Script >>> "$exceptionmsg
}
[System.GC]::GetTotalMemory($true) | out-null
if([System.IO.File]::Exists($YammerUnqUsrActivityCSV) -eq 'True'){
    Remove-Item $YammerUnqUsrActivityCSV
}
