[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egurkhaPath=(Get-Item Env:EGURKHA_INSTALL_DIR).value.ToString()
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy
clear


$testargs=$args
$reportingname='SBO\'+$testargs[0]

$ActDayNmTime=$testargs[1]
$splitActDayNmTime=$ActDayNmTime.split("#")
$activedays=$splitActDayNmTime[0]
$mTime=$splitActDayNmTime[1]

$username=$testargs[2]

$password=Eg-O365Dcr -EncStr $testargs[3]

$ProxyCrdlsServer=$testargs[4].ToString().Split('#')
$proxyUser=$ProxyCrdlsServer[0]
$proxyPass=Eg-O365Dcr -EncStr $ProxyCrdlsServer[1]
$proxyserverip=$ProxyCrdlsServer[2]
$proxyserver=$proxyserver='http://'+$proxyserverip


$domain=Eg-GetDomain -userName $username -Password $password -proxyUsr $proxyUser -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver

$azureVal=Eg-GetAzureEnv -UserName $username -subject 'O365_Graph'
$azureEnvArr=$azureVal.Split(',') 

$typePath=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'


$rptPath=$egurkhaPath+'\agent\'+$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
        } 
    }
}
#Date Format 
$CultureDateTimeFormat = (Get-Culture).DateTimeFormat
$DateFormat = $CultureDateTimeFormat.ShortDatePattern
$TimeFormat = $CultureDateTimeFormat.LongTimePattern
$DateTimeFormat = "$DateFormat $TimeFormat"

$sysDateFmt=Get-Date -Format 'MM/dd/yyyy HH:mm:ss'
$sysDat=[datetime]::ParseExact($sysDateFmt,'MM/dd/yyyy HH:mm:ss',$null) 
$startDat=$sysDat.AddMinutes(-$mTime)

try{
    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "CSOnlineUsr" -keyFileName "kCSOnlineUsr" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
    $TotalUsers= import-csv $csvfile | Where-Object {$_.UserPrincipalName -notlike '*#EXT*'}
    Remove-Item $csvfile
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'CSOnlineUsr' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kCSOnlineUsr' -InputFile $readfiles[4]
    Write-Host 'ReadFile:'$readfiles[3]
    }
    catch [System.Management.Automation.RuntimeException] {
        Write-Error -Message "File not found. The $reportingname location does not contain CSOnlineUser files."
    }
    catch{
        $errmsg=$_.Exception.Message
        $errstack=$_.Exception.StackTrace
        Write-Error -Message $errmsg
    }

$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$userdetilcsv = $rptPath+'\Userdetailreport'+$timenow+'.csv'
try{
$authString=$azureEnvArr[0]+$domain
$Resource=$azureEnvArr[1]
$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 "
}

$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)
                 $flag=$false
            }
        }
    }

Add-Type -Path $typePath
$usrdetilurl = $azureEnvArr[2]+"reports/getSkypeForBusinessActivityUserDetail(period='D7')" 
Eg-InvokeUrl -Url $usrdetilurl -filePath $userdetilcsv
try{
    $SkyUsrDetail= import-csv $userdetilcsv
    $NvrLogDetail=$SkyUsrDetail| Where-Object { $_.LastActivityDate -eq $null -or $_.LastActivityDate -eq ''  }
    $SkyUsrDetail=$SkyUsrDetail| Where-Object { $_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''  }| Sort-Object { [datetime]$_.'LastActivityDate' }  -Descending
    #$SkyUsrDetail=$SkyUsrDetail| Sort-Object { [datetime]$_.'LastActivityDate' }  -Descending
}catch{
    Write-Error -Message "File not found. The $reportingname location does not contain userdetial report "
}

	$DialUpConf=$TotalUsers|Where{$_.AcpInfo -ne $null -and $_.AcpInfo -ne ''}
	$UnAssignedUsers=$TotalUsers|Where{($_.RegistrarPool -eq $null -or $_.RegistrarPool -eq '') -and ($_.AssignedPlan -eq $null -or $_.AssignedPlan -eq '')}
    $UnAssigned = $UnAssignedUsers.Count
    $DialUp = $DialUpConf.Count
    $totalUser=$TotalUsers.Count
    $NvrLogUsers=$NvrLogDetail.Count
    $SoftUsers=0
    $RecCreUsers=0
    $RecChgUsers=0
    $ActUsers=0
    $InActUsers=0
# SoftDelete Users DD measure
	   
	    if($TotalUsers -ne $null){
		    foreach($Users in $TotalUsers){  
                 if($Users.SoftDeletionTimestamp -ne $null -and $Users.SoftDeletionTimestamp -ne ''){
                    $SoftDelTime = [DateTime]::ParseExact($Users.SoftDeletionTimestamp,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
                    if($SoftDelTime -ge $startDat){
                        $SoftUsers++
		                Write-Host '#ddSoftUsers'$Users.DisplayName '~!~'$Users.UserPrincipalName '~!~' $Users.SoftDeletionTimestamp
                    }
                }
# New Created Users DD measure
	            if($Users.WhenCreated -ne $null){
                     $WhenCreatedTime = [DateTime]::ParseExact($Users.WhenCreated,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
    		        if($WhenCreatedTime -ge $startDat){
                        $RecCreUsers++
		                Write-Host '#ddCreUsers'$Users.DisplayName '~!~'$Users.UserPrincipalName '~!~' $Users.WhenCreated
                    }
                }

# Recently Modified Users DD measure

                if($Users.WhenChanged -ne $null){
                    $WhenChanTime = [DateTime]::ParseExact($Users.WhenChanged,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
       		        if($WhenChanTime -ge $startDat){
                        $RecChgUsers++
		                Write-Host '#ddChgUsers'$Users.DisplayName '~!~'$Users.UserPrincipalName '~!~' $Users.WhenChanged
	            }
	        }
        }
    }

#DialUpConference Measure DD

	 if($DialUpConf -ne $null){
		    foreach($DialUpLoop in $DialUpConf){
		        if($DialUpLoop -ne $null -and $DialUpLoop -ne '' ){
                    $AcpInfo=[xml]$DialUpLoop.AcpInfo
		            Write-Host '#ddDialUpConf '$DialUpLoop.DisplayName '~!~' $DialUpLoop.UserPrincipalName'~!~'$AcpInfo.acpInformation.name'~!~'$AcpInfo.acpInformation.domain'~!~'$AcpInfo.acpInformation.participantPassCode'~!~'$AcpInfo.acpInformation.tollNumber
		        }
		    }
	    }


#UnAssigned Measure DD

	 if($UnAssignedUsers -ne $null){
	            for($i=0; $i -lt 10; $i++){
	                $UsrName=$UnAssignedUsers[$i].UserPrincipalName
	                $DspName=$UnAssignedUsers[$i].DisplayName
		        if($UsrName -ne $null -and $DspName -ne $null){
		            Write-Host '#ddUnAssigned '$DspName '~!~' $UsrName
		        }
		    }
	    }

#Inactive Measure DD
	 if($SkyUsrDetail -ne $null){
		    foreach($SkyUsrDetailLoop in $SkyUsrDetail){
		        if($SkyUsrDetailLoop -ne $null -and $SkyUsrDetailLoop -ne '' ){
                    if($SkyUsrDetailLoop.LastActivityDate -ne $null -and $SkyUsrDetailLoop.LastActivityDate -ne '' ){
                        $lastActivity=[datetime]$SkyUsrDetailLoop.LastActivityDate
                        #$lastActivity = [DateTime]::ParseExact($SkyUsrDetailLoop.LastActivityDate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
                        if ($lastActivity -gt  $sysDat.AddDays(-$activedays))
                        {			
                            $ActUsers++
                        }
                        elseif($lastActivity -lt $sysDat.AddDays(-$activedays))
                        {
                            if($InActUsers -lt 10){
                                Write-Host '#ddInactive '$SkyUsrDetailLoop.UserPrincipalName '~!~' $lastActivity
                            }
                            $InActUsers++
                        }
                    }
		        }
		    }
	    }

#NeverLog Measure DD
	 if($NvrLogDetail -ne $null){
            for($i=0; $i -lt 10; $i++){
                $UsrName=$NvrLogDetail[$i].UserPrincipalName
                if($UsrName -ne $null -and $UsrName -ne '' ){
                    Write-Host '#ddNeverLogUsers '$UsrName
                }
            }
    }
    Write-Host 'totalUsers:'$totalUser
	Write-Host 'unassigned:'$UnAssigned
    Write-Host 'DialUpConf:'$DialUp
    Write-Host 'SoftDeleteUsers:'$SoftUsers
    Write-Host 'CreatedUsers:'$RecCreUsers
    Write-Host 'ModifiedUsers:'$RecChgUsers
    Write-Host 'ActiveUsers:'$ActUsers
    Write-Host 'InActiveUsers:'$InActUsers
    Write-Host 'NvrLogUsers:'$NvrLogUsers

 if(Test-Path -Path $userdetilcsv){
      Remove-Item $userdetilcsv -Force
 }