<#
    /*****************************************************************************
    Author            :       Prabaharan.T
    Purpose           :       get the Message Center messages
    Created           :       31/01/2018
    Modified By       : 
#>
[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

$TestInputs=$args
$userName=$TestInputs[0]
$password=Eg-O365Dcr -EncStr $TestInputs[1]
$testFrequency=$TestInputs[2]
$proxycrdls=($TestInputs[3]).ToString().Split("#")
$proxyUsr=$proxycrdls[0]
$proxyPass=Eg-O365Dcr -EncStr $proxycrdls[1]
$proxyserverip=$TestInputs[4]
$azureVal=Eg-GetAzureEnv -UserName $userName
$azureEnvArr=$azureVal.Split(',')
if($proxyUsr.toString().toLower().Trim() -eq 'none') { $proxyUsr=$proxyUsr.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim() }
if($proxyserverip.toString().toLower().Trim().Contains('none')) { $proxyserverip=$proxyserverip.toString().toLower().Trim() }

$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
if(!$proxyserverip.Contains('none')){
    $proxyserver='http://'+$proxyserverip
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUsr -ne 'none' -and $proxyPass -ne 'none'){
        $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
        [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred   #[System.Net.CredentialCache]::DefaultNetworkCredentials
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
 }

$time=((Get-date).AddMinutes($testFrequency)).ToUniversalTime()
    $proxyserver='http://'+$proxyserverip
    $domain=Eg-GetDomain -userName $userName -Password $Password -proxyUsr $proxyUsr -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver


if($domain){

    [System.Collections.ArrayList]$incidentIDs=@()
    try{
        $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"
    }

    Function Eg-InvokeUrl(){
	    [CmdletBinding()]
        Param(
            [Parameter(Mandatory=$true, Position=1)]
            [String]$Url, 
            [Parameter(Mandatory=$true, Position=3)]
            [Object]$header               
        )

        Process
        {
           $query= Invoke-RestMethod -Method 'Get' -Headers $header -Uri $Url
           $query=$query.value
           return $query
        }
    }
    $ClientSecretDetails=$false
    $flag=$false
    foreach($inp in $GetInput){
        if($inp.StartsWith('[') -and $inp.Contains($domain)){
            $flag=$true
            $ClientSecretDetails=$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)
            }
            if($inp.Contains("TenantName")){
                $tenantID=$inp.ToString().Substring($inp.IndexOf('~')+1)
            }
            if($inp.Contains("Authority")){
                $authString = $inp.ToString().Substring($inp.IndexOf('~')+1)
                $authString=$authString+$domain
            }
            if($inp.Contains("Resource")){
                $Resource =$inp.ToString().Substring($inp.IndexOf('~')+1)
                $flag=$false            
            }
        }
    }

    if($ClientSecretDetails)
    {
        $path=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
        Add-Type -Path $path
        $Resource="https://manage.office.com"
        $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
        }

        $O365Servicesurl= "https://manage.office.com/api/v1.0/$domain/ServiceComms/Messages"
        $serv= Eg-InvokeUrl -Url $O365Servicesurl  -header $header

        foreach($evnt in $serv)
        {
            $msgType=($evnt.MessageType).Trim()
            if($msgType -eq 'MessageCenter')
            {
                $Status = $evnt.Status
                $ID= $evnt.Id
                $Title = $evnt.Title
                $AffectedTenantCount = $evnt.AffectedTenantCount
                $StartTime = $evnt.StartTime
                $EndTime= $evnt.EndTime
                $Message = $evnt.messages.MessageText
                $ActionRequiredByDate = $evnt.ActionRequiredByDate
                if($ActionRequiredByDate -eq $null){
                    $ActionRequiredByDate = '-'
                }
                $ActionType = $evnt.ActionType
                $Category = $evnt.Category
                $ExternalLink=$evnt.ExternalLink
                $UrgencyLevel=$evnt.Severity

                if($EndTime -gt $time){
                    Write-Host "##DDLINE##" "Messagecenter"  ~!~  $Category ~!~  $ID ~!~  $EndTime ~!~  $Title  ~!~  $StartTime ~!~  $ActionRequiredByDate ~!~  $ActionType ~!~  $ExternalLink ~!~  $UrgencyLevel ~!~
                    $msg = $Message -replace ‘<[^>]+>’,"”                      
                    if($msg.Contains("["))
                    {
                        $Msge = $msg.Split("[");
                        Write-Host   "##msage##" $Msge[0]
                    }else{
                        Write-Host   "##msage##" $msg
                    }
                }
            }
        }
    }
    else{
    Try{
        Write-Error -Message "GraphDetails File does not have the $domain client Secret details"
        Connect-MsolService -Credential $cred -AzureEnvironment $azureEnvArr[0]
        for($i=0; $i -le 2; $i++){
            $Json = (@{userName=$cred.username;password=$cred.GetNetworkCredential().password;} | convertto-json).tostring()
            $cookie = (invoke-restmethod -contenttype "application/json" -method Post -uri "https://api.admin.microsoftonline.com/shdtenantcommunications.svc/Register" -body $json).RegistrationCookie
            #preferredEventType -- "0" to represents a Service Incident, "1" to represent a Maintenance Event, and "2" to represent a Message Center communication 
            $load = (@{lastCookie=$cookie;locale="en-US";preferredEventTypes=@($i);} | convertto-json).tostring()
            $events = (invoke-restmethod -contenttype "application/json" -method Post -uri "https://api.admin.microsoftonline.com/shdtenantcommunications.svc/GetEvents" -body $load)
            $filtered=$events.events | Sort-Object -Descending -Property ID | select Status,ID,Title,AffectedTenantCount,AffectedServiceHealthStatus,starttime,EndTime,LastUpdatedTime,messages,ActionRequiredByDate,ActionType,Category,ExternalLink,UrgencyLevel 
                foreach($evnt in $filtered){
                    $Status = $evnt.Status
                    $ID= $evnt.ID
                    $Title = $evnt.Title
                    $AffectedTenantCount = $evnt.AffectedTenantCount
                    $AffectedServiceHealthStatus = $evnt.AffectedServiceHealthStatus
                    $StartTime = $evnt.starttime
                    $EndTime= $evnt.EndTime
                    $Message = $evnt.messages.messagetext
                    $ActionRequiredByDate = $evnt.ActionRequiredByDate
                    if($ActionRequiredByDate -eq $null){
                        $ActionRequiredByDate = '-'
                    }
                    $ActionType = $evnt.ActionType
                    $Category = $evnt.Category
                    $ExternalLink=$evnt.ExternalLink
                    $UrgencyLevel=$evnt.UrgencyLevel
                    if($i -eq 2){
                        if($EndTime -gt $time){
                              Write-Host "##DDLINE##" "Messagecenter"  ~!~  $Category ~!~  $ID ~!~  $EndTime ~!~  $Title  ~!~  $StartTime ~!~  $ActionRequiredByDate ~!~  $ActionType ~!~  $ExternalLink ~!~  $UrgencyLevel ~!~
                              $remtag = @('<a href=''','''>')
                                    for($i = 0 ; $i -lt $remtag.Length ;$i++){
                                        $Message=$Message.replace($remtag[$i], " ");
                                    }
                                        $msg = $Message -replace ‘<[^>]+>’,"”
                        
                              if($msg.Contains("[")){
                              $Msge = $msg.Split("[");
                              Write-Host   "##msage##" $Msge[0]
                              }else{
                              Write-Host   "##msage##" $msg
                              }
                        }
                    }       
                 }
            }
       }Catch{
	        Write-Error -Message "Error Occured in O365Msg Center -- " $_.Exception.Message
       }
    }

}






