Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Messaging
Imports Limilabs.Mail

Public Class frmEmail
    Private Logconfig As LogConfig
    Private Email As Email2

    Private Sub frmEmail_Load(sender As Object, e As EventArgs) Handles Me.Load
        Logconfig = New LogConfig(LogConfig.PathType.Temp, ProductName:="TestGUI.IMAP")
        Logconfig.Debug = True
        Email = New Email2(Logconfig)
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Using oClient = Email.New_IMAPConnection(txtServer.Text, txtUser.Text, txtPassword.Text, Email2.EmailSecurity.SSL)
            Dim oResult = Email.Test_IMAPLogin(oClient, "Inbox")

            If oResult = True Then
                AddLog($"Connection to {txtServer.Text} successful.")
            Else
                AddLog($"Connection to {txtServer.Text} failed!")
            End If
        End Using
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Using oClient = Email.New_IMAPConnection(txtServer.Text, txtUser.Text, txtPassword.Text, Email2.EmailSecurity.SSL)
            Dim oMessages = Email.Get_IMAPMessages(oClient, "Inbox")
            AddLog($"Found {oMessages.Count} Messages!")

            For Each oMessage In oMessages
                AddLog(oMessage.MessageID)
            Next
        End Using
    End Sub

    Private Sub AddLog(pMessage)
        ListBox1.Items.Add(pMessage)
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Using oClient = Email.New_IMAPConnection(txtServer.Text, txtUser.Text, txtPassword.Text, Email2.EmailSecurity.SSL)
            Dim oMessageId As String = txtMessageID.Text
            Dim oMail As IMail = Email.Get_IMAPMessage(oClient, oMessageId, "Inbox")
            Dim oFilename As String = IO.Path.GetTempFileName
            oMail.Save(oFilename)

            AddLog($"Mail saved to {oFilename}")

            Dim oEmailTempPath = Email.Remove_AttachmentsFromEmail(oFilename)

            AddLog($"Mail without attachments saved to {oEmailTempPath}")

            Dim oAttachments As List(Of String) = Email.Save_AttachmentsToDisk(oFilename)

            For Each oAttachment In oAttachments
                AddLog($"Attachmen saved to {oAttachment}")
            Next
        End Using
    End Sub

    Private Sub ListBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedValueChanged
        txtMessageID.Text = ListBox1.SelectedItem
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
        txtMessageID.Text = ListBox1.SelectedItem
    End Sub
End Class