##/*********************************************************************************************
##Author                :  Guravareddy.T
##Purpose               :  Display the Im(Instant message) and file transfer in skype
##Created               :  11/08/2018
##Modified By		    :

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
$reportingname='SBO\'+$testargs[0]
$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value


    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "Syallsessions" -keyFileName "kSyallsessions" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]
    [array]$userSession= import-csv $csvfile | Select-Object FromUri,ToUri,MediaTypesDescription,ConfInstance,conferenceurl,StartTime,EndTime,DialogId | Sort -property DialogId -Unique
    Remove-Item $csvfile
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'Syallsessions' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kSyallsessions' -InputFile $readfiles[4]
    Write-Host "ReadFile:"$readfiles[3]

$totalImsesions=0
$cmpltedImsessions=0
$totalsesduration=0
$filetransfersessions=0
$CurrentSessions=0
$totalcnferncecals=0
$CnfOrganisersCnt=0
$CnfParticpatedUsersCnt=0
$cnfurlStrtNendtime=@{} #map having conference url as key and start end times as values
$CnfrurlNusers=@{}  # conferenceurl and users hashtable
$Cnfrurlusrcnt=@{}  # conferenceurl and users count hashtable
$CnfrncurlNinstancid=@{} # confrence url as key and ConfInstance is value
$filetransfermap=@{} # key as from and to uri and  value as count 
$cnfpartisipant=New-Object System.Collections.ArrayList #total conference paraticipated users list
$CnfOrgslist=New-Object System.Collections.ArrayList #unique conference organised users list

#Date Format 
$CultureDateTimeFormat = (Get-Culture).DateTimeFormat
$DateFormat = $CultureDateTimeFormat.ShortDatePattern
$TimeFormat = $CultureDateTimeFormat.LongTimePattern
$DateTimeFormat = "$DateFormat $TimeFormat"


if($userSession){
    [array]$imusersessions=$userSession | Select-Object * |  Where-Object { $_.MediaTypesDescription -Like "*IM*"} 
    if($imusersessions)
    { 
        $totalImsesions=$imusersessions.count
        ## getting the only conference sessions from all im sessions
        [array]$cnfrncecals=$imusersessions | Select-Object * | Where-Object { $_.MediaTypesDescription -Like "*Conference*"} 
        ## geeting current running sessions (endtime of session is null)
        [array]$currentcals=$imusersessions | Select-Object FromUri,ToUri,MediaTypesDescription,StartTime,EndTime | Where-Object { $_.EndTime -eq "" }  | sort -Property FromUri,ToUri,MediaTypesDescription,StartTime -Unique | Sort-Object { $_.StartTime -as [datetime] } -Descending
        [array]$output=$imusersessions | Select-Object * | Where-Object { $_.EndTime -ne "" }
        $cmpltedImsessions=$output.Count
    }

    [array]$filetransfers=$userSession | Select-Object * | Where-Object { $_.MediaTypesDescription -eq ""}
}

foreach($ot in $output)
{  
    $mediastrttime = [DateTime]::ParseExact($ot.StartTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
    $mediaendtime = [DateTime]::ParseExact($ot.EndTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)

    $MediaDurationInMinutes = ( $mediaendtime - $mediastrttime).TotalMinutes
    $totalsesduration=$totalsesduration+$MediaDurationInMinutes               
}

foreach($crtcal in $currentcals  | select -First 10)
{
    $CurrentSessions=$currentcals.Count
    $curentmediatype=$crtcal.MediaTypesDescription.Replace("]["," ").Replace("]","").Replace("[","")
    $crtcalStartTime = [DateTime]::ParseExact($crtcal.StartTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
    $curntstrttime=Eg-ConvertTime -Time ($crtcalStartTime)
    $dd=''+$crtcal.FromURI +'~!~'+$crtcal.ToURI+'~!~'+'-'+'~!~'+$curntstrttime+'~!~'+'-'+'~!~'+$curentmediatype
    write-host 'currentcals##' $dd
    $dd=$null
}

if($filetransfers){$filetransfersessions=$filetransfers.Count}
foreach($filetranses in $filetransfers)
{
    $frmuri=$filetranses.FromURI
    $touri=$filetranses.ToURI

    $tempstr=$filetranses.FromURI+'#'+$filetranses.ToURI

    if($filetransfermap.Contains($tempstr))
    {
        $filetransfermap[$tempstr]++
    }
    else{

        $filetransfermap[$tempstr]=1
    }

}

foreach($filetranses in $filetransfermap.GetEnumerator() | Sort -property  Value -Descending | select -First 10)
{
    $key=(($filetranses.key).ToString()).split('#')
    $dd=''+$key[0]+'~!~'+$key[1]+'~!~'+$filetranses.value
    write-host 'filetransfer##' $dd
    $dd=$null
}

if($cnfrncecals)
{
    $totalcnferncecals=$cnfrncecals.count
    $cnfrncecals=$cnfrncecals | Select-Object * | Where-Object { $_.EndTime -ne ""}
    foreach($cfrccal in $cnfrncecals)
    {
        $cnfurl=$cfrccal.conferenceurl
        $instanceid=$cfrccal.ConfInstance
        $frmuri=$cfrccal.FromURI
        $touri= $cfrccal.ToURI
        $cfrccalStartTime = [DateTime]::ParseExact($cfrccal.StartTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
        $cfrccalEndTime = [DateTime]::ParseExact($cfrccal.EndTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
        $strtime=Eg-ConvertTime -Time  $cfrccalStartTime
        $endtme=Eg-ConvertTime -Time $cfrccalEndTime
        
        if($CnfrurlNusers.Contains($cnfurl))
        {
            $list=$CnfrurlNusers[$cnfurl]
            if(!$list.Contains($frmuri)) { $null=$list.Add($frmuri) }

            if(!$list.Contains($touri)) { $null=$list.Add($touri) }

            if(!$cnfpartisipant.Contains($frmuri)) { $null=$cnfpartisipant.Add($frmuri)}
            if(!$cnfpartisipant.Contains($touri)) { $null=$cnfpartisipant.Add($touri)}

        }
        else
        {
            $list=New-Object System.Collections.ArrayList
            $null=$list.Add($frmuri)
            if(!$list.Contains($touri))
            {
              $null=$list.Add($touri)  
            }
            $null=$CnfrurlNusers.Add($cnfurl,$list)
            $CnfrncurlNinstancid.Add($cnfurl,$instanceid)   #adding cnfurl and instnce id to map
        }
        
        
        if(!$cnfpartisipant.Contains($frmuri)) { $null=$cnfpartisipant.Add($frmuri)}
        if(!$cnfpartisipant.Contains($touri)) { $null=$cnfpartisipant.Add($touri)}


        ### getting the start time and end time of the each conference

        if($cnfurlStrtNendtime.Contains($cnfurl))
        {
            $strttime1=$cnfurlStrtNendtime[$cnfurl]['starttime']
            if(([datetime]$strtime) -lt ([datetime]$strttime1)){$cnfurlStrtNendtime[$cnfurl]['starttime']=$strtime}
            $endtime1=$cnfurlStrtNendtime[$cnfurl]['endtime']
            if(([datetime]$endtme) -gt ([datetime]$endtime1)){$cnfurlStrtNendtime[$cnfurl]['endtime']=$endtme}
        }
        else
        {
            $temp=@{}
            $temp.Add('starttime',$strtime)
            $temp.Add('endtime',$endtme)
            $cnfurlStrtNendtime.Add($cnfurl,$temp)
        }

    }
}

if($CnfrurlNusers)
{
   $totalcnferncecals=$CnfrurlNusers.count

    foreach($parcon in $CnfrurlNusers.GetEnumerator())
    {
        $cnfurl=($parcon.key).ToString()
        $CnfOrgUser=$cnfurl.Substring(4,$cnfurl.IndexOf(";"))
        $CnfOrgUser=$CnfOrgUser.Substring(0,$CnfOrgUser.IndexOf(";"))
        if(!$CnfOrgslist.Contains($CnfOrgUser)) { $null=$CnfOrgslist.Add($CnfOrgUser)}
        $cnt=$parcon.value.count
        $null=$Cnfrurlusrcnt.Add($parcon.key,$cnt)
	}

    foreach($entry in $Cnfrurlusrcnt.GetEnumerator() | sort -Property value -Descending | select -First 10)
    {
        $cnfurl=($entry.key).ToString()
        $CnfOrgUser=$cnfurl.Substring(4,$cnfurl.IndexOf(";"))
        $CnfOrgUser=$CnfOrgUser.Substring(0,$CnfOrgUser.IndexOf(";"))
        if($CnfrurlNusers[$cnfurl].Count -gt 5){$CnfrurlNusers[$cnfurl].Remove($CnfOrgUser)}
        $CnfPartUsrs=([String]($CnfrurlNusers[$cnfurl] | select -First 5)).Replace(" ",",")
        Write-Host  'conferencedd##' $CnfrncurlNinstancid[$entry.key]  '~!~' $CnfOrgUser '~!~' $entry.value '~!~'$CnfPartUsrs '~!~'($cnfurlStrtNendtime[$cnfurl]['starttime']).ToString() '~!~' ($cnfurlStrtNendtime[$cnfurl]['endtime']).ToString()
	}
}


if($CnfOrgslist) { $CnfOrganisersCnt=$CnfOrgslist.count }
if($cnfpartisipant) { $CnfParticpatedUsersCnt=$cnfpartisipant.count }

$totalsesduration=$totalsesduration.ToString('#.##')
Write-Host 'measures#' $cmpltedImsessions ~ $CurrentSessions ~ $totalsesduration ~ $totalcnferncecals ~ $CnfOrganisersCnt  ~ $CnfParticpatedUsersCnt ~ $filetransfersessions
