Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Controls.Primitives
Imports O2S.Components.PDFView4NET

Partial Public Class MainPage
    Inherits UserControl
    ''' <summary>
    ''' Initializes a new instance of the <see cref="MainPage"/> class.
    ''' </summary>
    Public Sub New()
        InitializeComponent()
        DataContext = Me
    End Sub

    ''' <summary>
    ''' Handles the Click event of the Browse control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    Private Sub Browse_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim browseFile As New OpenFileDialog()
        browseFile.Multiselect = False
        browseFile.Filter = "PDF Files (*.pdf)|*.pdf"

        Dim result As System.Nullable(Of Boolean) = browseFile.ShowDialog()
        Dim boolResult As Boolean

        If Boolean.TryParse(result, boolResult) Then
            PdfControl.Document = New PDFDocument()
            PdfControl.Document.Load(browseFile.File.OpenRead())
            FilePathTextBox.Text = browseFile.File.Name
            RefreshItemsSource()
        End If
    End Sub

    ''' <summary>
    ''' Refreshes the items source.
    ''' </summary>
    Private Sub RefreshItemsSource()
        DetailsListBox.ItemsSource = Nothing
        DetailsListBox.ItemsSource = FileAttachments
    End Sub

    Private _pdfFileAttachments As New List(Of PDFFileAttachment)()

    ''' <summary>
    ''' Gets or sets the file attachments.
    ''' </summary>
    ''' <value>
    ''' The file attachments.
    ''' </value>
    Public ReadOnly Property FileAttachments() As List(Of PDFFileAttachment)
        Get
            _pdfFileAttachments.Clear()
            For Each pdfFileAttachment As PDFFileAttachment In PdfControl.Document.FileAttachments
                _pdfFileAttachments.Add(pdfFileAttachment)
            Next

            Return _pdfFileAttachments
        End Get
    End Property

    Private _popup As New Popup()

    ''' <summary>
    ''' Handles the Click event of the AddAttachment control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    Private Sub AddAttachment_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim eaf As New EditAttachmentForm() With { _
         .Width = Me.ActualWidth, _
         .Height = Me.ActualHeight _
        }
        _popup.Child = eaf
        AddHandler eaf.Closed, AddressOf eaf_Add_Closed
        _popup.IsOpen = True
    End Sub

    ''' <summary>
    ''' Handles the Closed event of the eaf control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    Private Sub eaf_Add_Closed(ByVal sender As Object, ByVal e As EventArgs)
        Dim eaf As EditAttachmentForm = TryCast(_popup.Child, EditAttachmentForm)

        If eaf IsNot Nothing Then
            RemoveHandler eaf.Closed, AddressOf eaf_Add_Closed

            If eaf.AddAttachment Then
                ' Read the file in a byte array.
                Dim fs As FileStream = eaf.FileStream
                Dim fileData As Byte() = New Byte(fs.Length - 1) {}
                fs.Read(fileData, 0, fileData.Length)
                fs.Close()

                ' Create a file attachment object and add it to document.
                Dim fileAttachment As New PDFFileAttachment()
                fileAttachment.Data = fileData
                fileAttachment.Description = eaf.Description
                fileAttachment.FileName = eaf.FileName
                PdfControl.Document.FileAttachments.Add(fileAttachment)
            End If

            _popup.IsOpen = False
            _popup.Child = Nothing
            RefreshItemsSource()
        End If
    End Sub

    ''' <summary>
    ''' Handles the Click event of the EditDescription control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    Private Sub EditDescription_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim selectedAttachment As PDFFileAttachment = TryCast(DetailsListBox.SelectedItem, PDFFileAttachment)

        If selectedAttachment IsNot Nothing Then
            Dim eaf As New EditAttachmentForm() With { _
             .Width = Me.ActualWidth, _
             .Height = Me.ActualHeight _
            }
            eaf.BrowseButton.IsEnabled = False
            eaf.FileName = selectedAttachment.FileName
            eaf.Description = selectedAttachment.Description
            _popup.Child = eaf
            AddHandler eaf.Closed, AddressOf eaf_Modify_Closed
            _popup.IsOpen = True
        End If
    End Sub

    Private Sub eaf_Modify_Closed(ByVal sender As Object, ByVal e As EventArgs)
        Dim eaf As EditAttachmentForm = TryCast(_popup.Child, EditAttachmentForm)

        If eaf IsNot Nothing Then
            RemoveHandler eaf.Closed, AddressOf eaf_Modify_Closed

            If eaf.AddAttachment AndAlso DetailsListBox.SelectedItem IsNot Nothing Then
                Dim selectedAttachment As PDFFileAttachment = TryCast(DetailsListBox.SelectedItem, PDFFileAttachment)
                selectedAttachment.Description = eaf.Description
                RefreshItemsSource()
            End If

            _popup.IsOpen = False
            _popup.Child = Nothing
        End If
    End Sub

    ''' <summary>
    ''' Handles the Click event of the SaveAttachment control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    Private Sub SaveAttachment_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim selectedAttachment As PDFFileAttachment = TryCast(DetailsListBox.SelectedItem, PDFFileAttachment)

        If selectedAttachment IsNot Nothing Then
            Dim sfd As New SaveFileDialog()
            sfd.Filter = "Any Files (*.*)|*.*"
            Dim result As System.Nullable(Of Boolean) = sfd.ShowDialog()
            Dim boolResult As Boolean

            If Boolean.TryParse(result, boolResult) Then
                Dim stream As System.IO.Stream = sfd.OpenFile()
                Dim fileData As Byte() = selectedAttachment.Data
                stream.Write(fileData, 0, fileData.Length)
                stream.Flush()
                stream.Close()
                RefreshItemsSource()
            End If
        End If
    End Sub

    ''' <summary>
    ''' Handles the Click event of the RemoveAttachment control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    Private Sub RemoveAttachment_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim selectedAttachment As PDFFileAttachment = TryCast(DetailsListBox.SelectedItem, PDFFileAttachment)

        If selectedAttachment IsNot Nothing Then
            Dim result As MessageBoxResult = MessageBox.Show("Are you sure you want to delete the selected attachment?", "PDFView4NET", MessageBoxButton.OKCancel)

            If result = MessageBoxResult.OK Then
                PdfControl.Document.FileAttachments.Remove(selectedAttachment)
                RefreshItemsSource()
            End If
        End If
    End Sub

    ''' <summary>
    ''' Handles the Click event of the SaveDocument control.
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    Private Sub SaveDocument_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If PdfControl.Document IsNot Nothing AndAlso PdfControl.Document.PageCount > 0 Then
            Dim saveDialog As New SaveFileDialog()
            saveDialog.Filter = "PDF Files (*.pdf)|*.pdf"
            Dim result As System.Nullable(Of Boolean) = saveDialog.ShowDialog()
            Dim boolResult As Boolean

            If Boolean.TryParse(result, boolResult) Then
                Dim stream As System.IO.Stream = saveDialog.OpenFile()
                PdfControl.Document.Save(stream)
                stream.Close()
            End If
        Else
            MessageBox.Show("Nothing to save.", "Message", MessageBoxButton.OK)
        End If
    End Sub
End Class