Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Messaging.Mail.MailSession
Imports Limilabs.Client.IMAP
Imports Microsoft.Identity.Client

Public Class OAuth2
    Inherits BaseClass

    Private ReadOnly TenantId As String
    Private ReadOnly ClientId As String
    Private ReadOnly ClientSecret As String

    Public Const O365_SCOPE = "https://outlook.office365.com/.default"
    Public Const O365_SERVER = "outlook.office365.com"

    Private _AccessToken As String
    Public ReadOnly Property AccessToken
        Get
            Return _AccessToken
        End Get
    End Property

    Public Sub New(pLogConfig As LogConfig, pTenantId As String, pClientId As String, pClientSecret As String)
        MyBase.New(pLogConfig)
        TenantId = pTenantId
        ClientId = pClientId
        ClientSecret = pClientSecret
    End Sub

    Public Function GetAccessToken() As String
        Logger.Debug("Fetching Access Token..")

        Try
            ' Create the application, which is defined in
            ' Microsoft.Identity.Client
            Dim oApp = ConfidentialClientApplicationBuilder.
                Create(ClientId).
                WithTenantId(TenantId).
                WithClientSecret(ClientSecret).
                Build()

            ' Request an access token
            Dim oScopes = New List(Of String) From {O365_SCOPE}
            Dim oResult = oApp.
                    AcquireTokenForClient(oScopes).
                    ExecuteAsync().Result

            Logger.Debug("Access Token fetched.")

            Return oResult.AccessToken
        Catch ex As Exception
            Logger.Warn("Could not request access token!")
            Logger.Error(ex)
            Return Nothing
        End Try
    End Function
End Class
