<#
    /*****************************************************************************
    Author            :       Mounika Kuna
    Purpose           :       Provides Yammer Users By Device 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
[System.GC]::GetTotalMemory($true) | out-null
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$YammerUsersByDeviceCSV=$rptPath+'\YammerUsersByDevice'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $YammerUsersByDeviceCSV

Eg-InvokeGraphUrl -Url "https://graph.microsoft.com/v1.0/reports/getYammerDeviceUsageUserCounts(period='D7')" -filePath $YammerUsersByDeviceCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource

$TotalYammerUsersByDevice=Import-Csv $YammerUsersByDeviceCSV -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
    $UnqUsrsbyDev =$TotalYammerUsersByDevice | Where-Object { [datetime]$_.ReportDate -eq $actualdate }       
    if($UnqUsrsbyDev)
    {
        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($UnqUsrsbyDev.Web -eq ""){ $Web = 0 }else{ $Web = $UnqUsrsbyDev.Web }
    if($UnqUsrsbyDev.WindowsPhone -eq ""){ $WindowsPhone = 0 }else{ $WindowsPhone = $UnqUsrsbyDev.WindowsPhone }
    if($UnqUsrsbyDev.AndroidPhone -eq ""){ $AndroidPhone = 0 }else{ $AndroidPhone = $UnqUsrsbyDev.AndroidPhone }
    if($UnqUsrsbyDev.iPhone -eq ""){ $iPhone = 0 }else{ $iPhone = $UnqUsrsbyDev.iPhone }
    if($UnqUsrsbyDev.iPad -eq ""){ $iPad = 0 }else{ $iPad = $UnqUsrsbyDev.iPad }
    if($UnqUsrsbyDev.Other -eq ""){ $Other = 0 }else{ $Other = $UnqUsrsbyDev.Other }
    if($Web.Length -ge 0){
    $Web='info&Metrics='+'Web'+'~'+$Web    
    Write-Host $Web
    }
    if($WindowsPhone.Length -ge 0){
    $WindowsPhone='info&Metrics='+'WindowsPhone'+'~'+$WindowsPhone
    Write-Host $WindowsPhone
    }
    if($AndroidPhone.Length -ge 0){
    $AndroidPhone='info&Metrics='+'AndroidPhone'+'~'+$AndroidPhone
    Write-Host $AndroidPhone
    }
    if($iPhone.Length -ge 0){
    $iPhone='info&Metrics='+'iPhone'+'~'+$iPhone
    Write-Host $iPhone
    }
    if($iPad.Length -ge 0){
    $iPad='info&Metrics='+'iPad'+'~'+$iPad
    Write-Host $iPad
    }
    if($Other.Length -ge 0){
    $Other='info&Metrics='+'Other'+'~'+$Other
    Write-Host $Other
    }
}catch{    
    $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	Write-error "Error Occured in Yammer Users by Device Script >>> "$exceptionmsg
}
[System.GC]::GetTotalMemory($true) | out-null
if([System.IO.File]::Exists($YammerUsersByDeviceCSV) -eq 'True'){
    Remove-Item $YammerUsersByDeviceCSV
}
