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


$testargs=$args
$Rptcrds=$testargs[4].split("#")
$reportingname='MTM/'+$Rptcrds[0]
$testFrequency=$Rptcrds[1]

$CultureDateTimeFormat = (Get-Culture).DateTimeFormat
$DateFormat = $CultureDateTimeFormat.ShortDatePattern
$TimeFormat = $CultureDateTimeFormat.LongTimePattern
$DateTimeFormat = "$DateFormat $TimeFormat"
	
try{
    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "MTMdAuditOper" -keyFileName "kMTMdAuditOper" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
    $usractivites= import-csv $csvfile | Where-Object { $_.RecordType -eq 'MicrosoftTeams' -and $_.Operations -eq 'TeamsSessionStarted'} | select CreationDate,UserIds | Sort-Object { [DateTime]::ParseExact($_.CreationDate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None) } -Descending

    Remove-Item $csvfile       
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'MTMdAuditOper' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kMTMdAuditOper' -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 MTM usr Activities files."
    }
    catch{
        $errmsg=$_.Exception.Message
        $errstack=$_.Exception.StackTrace
        Write-Error -Message $errmsg
    }

$latestUsrlogins=@{}
if($usractivites)
{
    foreach($usrlogin in $usractivites)
    {
        if(!$latestUsrlogins[$usrlogin.UserIds])
        {
          try{
          $UsrCrtionDate=[DateTime]::ParseExact($usrlogin.CreationDate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None) 
          }
          catch{
              $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	          Write-error "Error Occured in Teams User logins Test --  $exceptionmsg"
              $UsrCrtionDate=$usrlogin.CreationDate
          }
          $latestUsrlogins[$usrlogin.UserIds]=$UsrCrtionDate  
          Write-Host 'userlogin#' $usrlogin.UserIds ~!~ $UsrCrtionDate
        }
    }

}


