'  
'   Rebex Sample Code License
' 
'   Copyright 2026, REBEX CR s.r.o.
'   All rights reserved.
'   https://www.rebex.net/
' 
'   Permission to use, copy, modify, and/or distribute this software for any
'   purpose with or without fee is hereby granted.
' 
'   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
'   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
'   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
'   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
'   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
'   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
'   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
'   OTHER DEALINGS IN THE SOFTWARE.
' 

Imports System
Imports System.Text
Imports Rebex.Mail
Imports Rebex.Mime
Imports Rebex.Mime.Headers

Module MsgAddressFormatter
    Function ToString(ByVal address As MsgAddress) As String
        If address.AddressType = MsgAddressType.Unknown Then
            Return String.Empty
        ElseIf address.AddressType = MsgAddressType.Smtp Then
            Return New MailAddress(address.SmtpAddress, address.DisplayName).ToString()
        Else
            Return address.ToString()
        End If
    End Function

    Function ToString(ByVal addresses As MsgAddressCollection) As String
        Dim sb As New StringBuilder()

        For Each address As MsgAddress In addresses
            If sb.Length > 0 Then sb.Append(", ")
            sb.Append(ToString(address))
        Next

        Return sb.ToString()
    End Function

    Function ParseSmtpAddressCollection(ByVal text As String) As MailAddressCollection
        If String.IsNullOrEmpty(text) Then Return Nothing

        Try
            Dim list As New MailAddressCollection(text)

            For Each address As MailAddress In list
                If String.IsNullOrEmpty(address.User) OrElse String.IsNullOrEmpty(address.Host) Then Return Nothing
            Next

            Return list
        Catch x As MimeException
            If x.Status <> MimeExceptionStatus.HeaderParserError Then Throw
            Return Nothing
        End Try
    End Function
End Module
